Take the 2-minute tour ×

I am trying to convert this .json.rabl view to .json.erb and since im very new to ruby, I am looking for direction in achieving this. What will be the best way to go about this?

object @perform
attributes :id => :team_id 
attributes :perform_id
node(:fb_user_id) {|x| x.user.fb_user_id.to_s}
node(:first_name) {|x| x.user.first_name}
node(:last_name) {|x| x.user.last_name}
attributes :level, :jersey, :height, :weight, :positions
node(:stat_source) {|x| Stat::SOURCES.key(x.stat_source)}

if !@nomvps node({}, :if => lambda{ |m| @event.present? }) do |x| { mvp_votes: Vote.player_vote_count(@event.id, x.id) } end end

if !@nostats && (@_options[:event] || @event) node :stats do |perform| Hash[*perform.source_stats.where(event_id: (@_options[:event].try(:id) || @event.id)).map{|x|[x.name, x.value]}.flatten] end end

share|improve this question

2 Answers 2

up vote 3 down vote accepted

Erb is the reverse of a templating language like rabl - you create the json you want, and then insert the values with erb, rather than defining the structure with code as in rabl.

In erb surrounding text with <% %> indicates some ruby code (for assigning, loops etc):

<% x = "output" %>

and <%= %> (NB = sign) indicates ruby code (any code) which will be output to the template by calling to_s:

<%= x.to_json %>

Anything not surrounded by those symbols is output exactly as it is.

So you should be able to just create the json you want with fake values, and then put in the calls to the relevant ruby code to get the real values at runtime. e.g. something like this fragment (not familiar with rabl so the format of json may need adjustment):

[{  "perform" :
    "id" : <%= @perform.team_id %>, 
    "user" : <%= @perform.perform_id %>,


<% if !@nomvps %>
  <% node({}, :if => lambda{ |m| @event.present? }) do |x|   %>
  mvp_votes: <%= Vote.player_vote_count(@event.id, x.id) %>
  <% end %>
<% end %>

For objects which map cleanly to json as a hash for example you could also consider creating to_json methods instead of laying them out in a template like this, but for a complex structure like this without a clean mapping a template might be best.

I'd start with the json you want in a file named xx.json.erb (pure json), then start inserting values using erb.

share|improve this answer

Maybe it's not an answer to the exact question, but the endorsed way to do JSON views in rails is using jbuilder.

The API of JBuilder is very similar to the RABL one, but it's done by the very same rails core team, so it integrates with all the internals, like cache helpers (in the future also cache dependence), partials etc.


share|improve this answer

Your Answer


