Tuesday 10 December 2013

Learning Ember.js and Rails Part 1 (of many!)

I’m starting on a new, massive, application. I don’t like to make things easy on myself so instead of doing this in my usual RoR/jQuery stack I am jumping in and doing this with:
  • Ruby 2
  • Rails 4
  • Ember.js
This presents some challenges, not the least of which is Ember.js. I’ve never used a front end framework before. But I can see the power of it, plus, one of the key features of this new app is that it will provide a data api. With Ember.js, I believe, almost all interaction with the data will be through an api, so it seems like a good start and a way to sanity check what is coming in and out to other consumers of this api.

I know I suck at writing blog posts, but, I will try and document this journey because I have looked around and there doesn’t appear to be too many resources for people doing this. Everything I have found is much too simple and is not for the experienced Rails developer.

I did find one good resource from Tony Coconate (http://www.devmynd.com/blog/2013-3-rails-ember-js) and I am starting off from that. Now, that may or may not be a good idea!

Setup

I set up a new rails app. Then chucked some stuff into the Gemfile:
# front end
gem 'ember-rails'
gem 'ember-source'
gem 'ember-auth-rails'
gem 'ember-auth-source'

Create Resources

After, my first steps were to all but ignore the front end. 

I created my models as resources, like in Tony’s article. For example:

rails g resource Trainer name:string additional_info:text provider:references provider_key:string —no_helper

This means you end up with:
  • a controller, 
  • a model
  • a serializer - from active model serializer
  • a db migrate script 
  • two coffee script views (trainer and trainers)
  • entries in routes.rb
Moving Controllers

Again, as per Tony’s article, I am going to use Ember Data (whether or not it is ready for prime time now is not too important. This app won’t see the light of day for months yet). So, I move all the controllers from /app/controllers to /app/controllers/api/v1 and put Api::V1:: at the front. I also put in standard actions. So now my controller looks like this:

class Api::V1::TrainersController < ApplicationController
    respond_to :json

    def index
        respond_with Trainer.all
    end

    def show
        respond_with Trainer.find(params[:id])
    end
end

Modify Routes

I also modify routes.rb to look like this:

namespace :api do
    namespace :v1 do
        resources :trainers
    end
end

At this point I can point my browser at localhost:3000/api/v1/trainers.json and get a list (assuming I have data!) or to localhost:3000/api/v1/trainers/1.json to get the single record.

So far so good.

In my mind the data side of the app is on the way. I will not worry about any more Rails stuff for now.

Next is learning Ember.js 

No comments: