Tips and tricks

databyte edited this page Jun 27, 2012 · 12 revisions

How to output some random, not directly related items

Say you want to return a few things, for example a proper data item, and also a status code and message. You don't want to create an object just to hold these items for the output view, but instead just use them all directly in the output view. To do this, make the objects instance variables, like usual, eg:

@foo = "bar"
@pop = 123

Then use the "object false" facility in the RABL template, like so:

object false
node(:foo) { @foo }
node(:pop) { @pop }

If @foo is a more complex object, you can just specify which of its attributes to use by using a child() call instead, like this:

model:

class Car
  attr_accessor :car_make, :car_name
end

controller:

@cars = Car.all
@status = "ok"

view:

object false
child(@cars) { attributes :car_name, :car_make }
node(:status) { @status }

output (assuming json roots are turned off):

{ status:"ok", [{ car_make:"Toyota", car_name:"Prius"},...]}

When to use Child and Node

Child and Node traverses the objects differently. Child doesn't use a block to pass in the current object as it navigates through the object and alters the idea of 'self' whereas Node passes in the current object and does not change 'self'.

object @foo         # root_object is @foo

child :target do    # root_object is now @foo.target
  attribute :bar    # comes from @foo.target.bar
end

node :hello do |hi| # root_object is still @foo
  hi.bar            # comes from @foo.bar
end