Skip to content

Calling a lambda in the api template

fabrik42 edited this page Apr 20, 2011 · 2 revisions

Calling a lambda in the api template

Sometimes calling a method is just not easy enough or you need to get a special value at the moment when the model gets rendered.

In this case you can easily pass a lambda or a Proc to the api template that gets called when the model is rendered and its return value will be used as the value of the attribute.

It is important that you always pass the :as option together with a lambda so the name of the attribute can be set.

Tip: The lambda block is always called with one parameter: The instance of the model that gets rendered.

class User < ActiveRecord::Base

  acts_as_api

  api_accessible :calling_a_lambda do |t|
    t.add lambda{|user| user.full_name.upcase  }, :as => :all_caps_name
  end

end