on
Rails and Ember.js Integration Notes
After some attempts to use Backbone.js for a project, I decided to use Ember.js. It didn’t take a long time to learn it and to get what I needed working. Prior to this, I spent a lot of time learning Backbone.js because of all options, it’s most lightweight and flexible.
I found very few tutorials and books about Ember.js compared to Backbone.js but strangely, it was easier to learn (for me at least).
I have a few notes which are also published along with a test Rails application.
For now, I have about 2 minor improvements which are based on some “best practices.” I have more to share about this later.
Use nested module/class definitions instead of compact style
module Api
module V1
class LeadsController < ApplicationController
respond_to :json
end
end
end
The code above is preferred over:
class Api::V1::LeadsController < ApplicationController
respond_to :json
# methods
end
The config/routes.rb
should use scope module
:
namespace :api, defaults: { format: 'json' } do
scope module: :v1 do
resources :leads
end
end
A JSON API document should be identified by the media type application/vnd.api+json
This is based on a standard for building JSON API. Similarly mentioned in HTTP API Design
We achieve this by autoloading a module:
# lib/api_constraints.rb
class ApiConstraints
def initialize(options)
@version = options[:version]
@default = options[:default]
end
def matches?(req)
@default || req.headers['Accept'].include?("application/vnd.myapp.v#{@version}")
end
end
And updating routes to use this module:
# config/routes.rb
namespace :api, defaults: { format: 'json' } do
scope module: :v1, constraints: ApiConstraints.new(version: 1) do
resources :leads
end
end
Making this work with Ember.js is simple. Simply include headers on app/assets/javascripts/store.js.coffee.
# app/assets/javascripts/store.js.coffee
DS.RESTAdapter.reopen
namespace: 'api'
headers: {
"Accept": "application/vnd.myapp.v1+json"
}
Most of the API’s I create require headers for authentication.
Both Rails and Ember.js are great. There aren’t a lot of style guides about Rails and Ember.js. I found one but there aren’t a lot on that repo. I want to document what I find to be good practices. Probably would write about testing next time!
I hope someone would start a style guide of sorts. Currently I am still exploring Ember.js, Backbone.js and Angular.js. It starts to get confusing when you consider React.js as well. This React vs. Ember presentation may help you decide a bit. Honestly, just try everything and choose! That is what I do.