Thursday, February 14, 2013

Sugar is an amazing JavaScript library that extends a lot of the native JavaScript types and brings in similar functionality to JavaScript that ActiveSupport brings to Ruby. It is usually overlooked when compared to the similar JavaScript library underscore.js although it provides the same functionality plus additional features.

I find myself using Sugar on a daily basis these days working with AngularJS and Node.js. I prefer it over underscore.js for a few reasons.

  1. Sugar extends native types so I don't have to use a wrapper method on arrays, numbers and strings (although you need to wrap objects).
  2. Sugar has a much wider variety of methods including methods for strings, numbers and dates.
  3. Sugar's syntax is more natural to me coming from Ruby on Rails and ActiveSupport.
  4. It's modular so you can pick and choose the functionality that you need.

I still think underscore.js is an amazing library and if you are looking for a speedier, lighter alternative it does the job just fine. As a bonus underscore.js also includes templating built in something that Sugar is sorely lacking.

Here are a few examples of methods that I find myself using frequently.

Relative Time

I really love time_ago_in_words when working with Rails. Sugar has the same functionality although a little bit different.

Date.create('2013-02-10').relative(); // 5 days ago

As a bonus, a filter that I use in AngularJS frequently:

app.filter('timeAgo', function () {
  return function (date) {
    return Date.create(date).relative();

Then in your template you can use the following:

<p class="date">{{updated|timeAgo}}</p>

Creating Slugs

I build a lot of CMS type systems, most of the time I will use slugs for friendly urls. Before I would generate them based on the name or title server side but now I usually add a field below the title that generates the slug based on the title and still allows the author to modify it if they want.


The parameterize method above strips out any non [a-zA-z0-9] characters and replaces them with dashes.

Finding elements in Arrays

Sugar makes it really easy to find elements in arrays. It extends the array prototype with the find method and allows you to search using a string, number, array, object, or alternately test against a function or regex.

var games = [
  {id: 1, title: 'Super Mario World'},
  {id: 2, title: 'Halo 4'},
  {id: 3, title: 'Grand Theft Auto'},
  {id: 4, title: 'Sonic the Hedgehog'},
  {id: 5, title: 'God of War'}

var mario = games.find(function (g) {
  return g.title == 'Super Mario World';

var sonic = games.find(function (g) {
  return g.id == 4;

These are just a few examples of Sugar's functionality. To learn more check out the examples on their site and read the docs and API.

Sunday, December 9, 2012

I've put together a simple demo that integrates Polytalk with Meteor. The app allows you to retrieve, create and delete posts from a Ruby Polytalk server that is exposing a simple Post ActiveRecord model.

The app utilizes Meteor's latency compensation and keeps the database updated on both the Meteor app and the Ruby server. We do this by loading in all the posts from the server into a Meteor collection that we keep updated every time you create or delete a post.

For the most part the code will look familiar to anyone who's played around with a Meteor app before. We have 3 methods on the server that we expose to the client that will load posts, save a post and remove a post. The one tricky part is in the loadPosts method that synchronizes the Meteor collection with the posts from the Ruby server.

# Load posts from Polytalk
loadPosts = ->

  # Remove all posts from collection

  postsRequest =
    class: 'Post'
    method: 'find'
      type: ':all'
        order: 'id DESC'
        limit: 10

  client.call postsRequest, (response) ->
    posts = response.map (post) -> post.post
    for post in posts
      Fiber ->
        Posts.insert({dbid: post.id, title: post.title, body: post.body, time: Date.now()})

  return true

Once we receive the posts from the server we need to insert the posts into the collection in a Fiber so it doesn't lock up other parts of the application.

Run the demo

The git repository has the app and the ruby server included. To get it running you will need to cd into the ruby_server directory and run bundle to download the gems. Once downloaded while in the ruby_server directory run ruby server.rb to start the Polytalk server. This will setup the database and expose the Post model to the client.

Once the Ruby server is running you can cd back to the root of the project and run the Meteor app with meteor. You should now be able to visit the app in your browser and start adding and removing posts.

That's it, let me know if you have any questions or suggestions below in the comments.

Saturday, December 8, 2012

I just pushed some changes to the Polytalk Ruby Gem to allow symbols to be used as arguments. Also all keys in hashes now default to symbols when using the Ruby server. To use use a symbol instead of a string you simply prepend a colon : infront of the argument.

For instance to call the find method on the post model and return the first post I would do the following:

client = Polytalk::Client.new({ port: 9090 })

request = {
    class: 'Post',
    method: 'find',
    arguments: {
      type: ':first'

puts client.call(request)

And to implement the server I would do the following:

class Post < ActiveRecord::Base

server = Polytalk::Server.new({ port: 9090 })
server.run do |connection, request|
  response = server.call(request)
  server.push(connection, response)

I'm planning a post of using Polytalk with Meteor in the near future. Stay tuned!

Thursday, December 6, 2012

Yesterday I blogged about Phalcon, the PHP framework written in C. At the end of the post I said I would show you guys how to setup Phalcon on Heroku. After a bit of research and building out a demo app I have it up and running on Heroku. I've simplified the process into 3 steps.

(Optional) Clone my demo application

I built a simple blogging application that utilizes Phalcon's Micro MVC router (think Sinatra), models with relationships, views, autoloading and a few other features. It's very rudimentary containing only a few methods to create posts, view posts and add comments to posts.

$ git clone https://github.com/andruu/Phalcon-on-Heroku.git

Create a new application on Heroku

Make sure that you have the Heroku toolbelt installed and you are logged into your Heroku account. Next you will have to create your app using a custom buildpack. Buildpacks allow you to customize your instance with different modules and allow you to configure it exactly how you want it. Create your new application and commit the code with the command below.

$ heroku create phalcon --buildpack git://github.com/elct9620/heroku-buildpacks-php-with-phalcon.git
$ git push heroku

Add the ClearDB MySQL add-on

I was having trouble getting Heroku's built in PostgreSQL to work well with Phalcon but no worries Heroku has a free add-on for MySQL. Run the following command to setup your MySQL database.

$ heroku addons:add cleardb:ignite

Setup the database

Now you just have to create your tables. Your MySQL connection information is stored on Heroku as an environment variable which is already detected if you are using the demo app provided. You will need to setup the tables before you can use your app. You can get the credentials by running the following command.

$ heroku config

Look for the CLEARDB_DATABASE_URL variable. You can now use this to login to MySQL via the command line or your favourite GUI. Once logged in run the following SQL to create your tables.


-- ----------------------------
--  Table structure for `comments`
-- ----------------------------
CREATE TABLE `comments` (
  `post_id` int(11) DEFAULT NULL,
  `name` varchar(255) DEFAULT NULL,
  `comment` text,
  PRIMARY KEY (`id`)

-- ----------------------------
--  Table structure for `posts`
-- ----------------------------
CREATE TABLE `posts` (
  `title` varchar(255) DEFAULT NULL,
  `body` text,
  PRIMARY KEY (`id`)


That's it you should now be up and running. Test out your application by running.

$ heroku open
Wednesday, December 5, 2012

Over the past few years the PHP community has matured and evolved immensely The language itself has seen some amazing new features over the past few releases. We now have array literals ($names = ['andrew', 'tom', 'steve'];), function array dereferencing ($first_name = explode(' ', $name)[0];), anonymous functions, closures and traits (similar to mixins). There is composer a package manager similar to npm or bundler and a huge repository Packagist to go along with it.

Although my focus has been on Ruby on Rails and Node.js recently I still use PHP in my day to day work. For the last 5 years CakePHP has been my framework of choice but with the crop of new frameworks emerging I decided I would do some research and see what else is out there.

It seems like Laravel is getting a lot of recognition these days as it rightfully should. It utilizes most of PHP's new features, has amazing documentation, a budding community and a consistent API. All of these features are great but at the end of the day it's not that different from CakePHP which I've already invested over 5 years learning (mastering). The same goes for a bunch of the new frameworks that have either been updated (Symfony 2, Zend Framework 2) or emerged on the scene (Fuel).

Along comes Phalcon

Phalcon is similar in the sense that it is a PHP MVC framework, but what sets it apart is that it's a PHP extension written in C. This has a lot of advantages.


In benchmarks it is shown to be an order of magnitude faster than most popular PHP frameworks out today. This makes sense, since the code is compiled for your system and doesn't have to be interpreted at runtime.

Forget about framework files

Another amazing feature is that all the classes and functions are available to you anytime anywhere. No need to download a 40MB framework every time you want to start up a new project. All of the components are loosely coupled so if you want to write a simple script that just uses Phalcon's ORM classes, just call them like you would any other php functions. No need for includes and managing files.


Installation was a breeze on my MacBook Air. Initially I tried installing via homebrew but that was giving me problems. I ended up following the instructions on their website, restarted my server and away I went.

Creating the extension:

git clone git://github.com/phalcon/cphalcon.git
cd cphalcon/build
sudo ./install

Add extension to your php.ini


Restart the webserver


This won't work on most shared hosting accounts since this has to be installed usually at a root level although I wouldn't be surprised if some hosts started adding it to their default installations in the future.

What's next

I plan on writing a few more posts on Phalcon in the next week. Next up will be setting Phalcon up on Heroku. Stay tuned!