Skip to content

Conditional statements for adding a field to the api template

fabrik42 edited this page Apr 24, 2011 · 2 revisions

Conditional statements for adding a field to the api template

Very much like for ActiveRecord callbacks or validations, you can pass an :if or :unless option when adding a field to an api template.

The value of this options must be either a Symbol or a lambda/Proc. It gets called by acts_as_api when the template is rendered.

When a Symbol is passed, acts_as_api will try to call a method with the same name on the model instance. In case a Proc is passed, it will be called with the model instance passed as the first and only parameter.

When using the :if option, the field will only be added if the passed condition returns a value that is not nil or false.

On the other side, when using the :unless option, the field will only be added if the passed condition returns a value that is nil or false.

See an example using a symbol:

class User < ActiveRecord::Base

  acts_as_api

  api_accessible :user_show do |t|
    t.add :first_name
    t.add :last_name
    t.add :age
    t.add :favorite_beer, :if => :is_adult?
  end

  def is_adult?
    age >= 21
  end
end

Using a Proc:

class User < ActiveRecord::Base

  acts_as_api

  api_accessible :user_show do |t|
    t.add :first_name
    t.add :last_name
    t.add :age
    t.add :favorite_beer, :if => lambda{|u| u.age >= 21 }
  end
end

In both cases the field favorite_beer will only be added to the response if the user's age is at least 21.