Serving Ember.js With Rails 3.1's Asset Pipeline

Last week we spent some time modifying Kisko Labssproutcore-rails gem to use the latest build of Ember.js. emberjs-rails is a fairly simple wrapper that add’s support for serving Handlebars templates from the asset pipeline using a hjs file extension. It also serves Ember’s html5 boilerplate template as a layout called ember. ┬áHere’s a quick run through:

First, start with an empty Rails 3.1 installation:

Next, install an empty Rails application:

Add emberjs-rails to your application’s Gemfile and run bundler:

Generate a controller to serve your Ember.js application from:

Setup basic routing for your new controller: config/routes.rb

Modify your new controller to use the ember layout included in emberjs-rails, this is a slight modification of the html5 boilerplate file included with Ember.js’ starter kit: app/controllers/hello_controller.rb

Create a handlebars template to use within your Ember.js application: app/assets/javascripts/views/hello.js.hjs

Create a view on for your home_controller to include your new handlebars view, which the asset pipeline will compile for you automatically. You can also include additional information for the html meta tags and page title if you want to: app/views/hello/index.html.erb

Lastly, create your Ember.js application and create a view from the template above. The rails 3.1 ships with CoffeeScript support by default, so we’ve created the app using CoffeeScript to show how it’s done:

Now if you start your server and browse to it (usually localhost:3000 you should see a large “Hello World!” which is rendered using the template and the property on the view we created. You can also open up your browser’s JavaScript console and change the value of the text property on the hello_view object and watch it dynamically change on screen.

We hope that gives you enough information to go forth and JavaScript. Enjoy!