Subscribe to
Posts
Comments

Didn’t you always want to write your Rails views as plain Ruby objects? — “What?”, I hear you say. No, I haven’t lost my mind and the idea is quite sensible (or so I hope), once you add the restriction that it is JSON-formatted data that you want to return.

Say you need to set up some hashes or arrays for rendering to JSON. This is best done in Ruby and it is clearly a view concern. So let’s do it in the views. Like this:

  # app/controllers/movies_controller.rb
  def index
    respond_to do |format|
      format.json do
        @movies = Movie.all
        @count = Movie.count
        render :template => 'movies/index.json.rb'
      end
    end
  end

  # app/views/movies/index.json.rb
  {
    :identifier => Movie.primary_key,
    :totalCount => @count,
    # render @movies does not work as it insists on returning a string
    :items => @movies.map { |m| render(m) }
  }

  # app/views/movies/_movie.json.rb
  {
    :id => movie.to_param,
    :title => movie.title,
    :releaseDate => movie.release_date
  }

Getting it

  • github
  • $ sudo gem install mschuerig-ruby_template_handler

Let your Rails app know about it

In the appropriate place in config/environment.rb add

config.gem "mschuerig-ruby_template_handler", :lib => 'ruby_template_handler'

Leave a Reply

Fork me on GitHub