Skip to content

Model callbacks (including an example for caching api responses)

fabrik42 edited this page Jun 13, 2011 · 2 revisions

Using model callbacks

There are three optional callbacks that occur before, after and around the as_api_response call.

before_api_response
after_api_response
around_api_response

All three take the requested api_template as an argument and are placed in the model that is being rendered

class User < ActiveRecord::Base

  acts_as_api

  api_accessible :public do |t|
    t.add :first_name
    t.add :last_name
  end

  def before_api_response(api_template)
    puts "Called before the response hash is rendered with api_template: #{api_template}"
  end
  
  def around_api_response(api_template)
    puts "Called around the response hash is rendered with api_template: #{api_template}"
    yield
  end
  
  def after_api_response(api_template)
    puts "Called after the response hash is rendered with api_template: #{api_template}"
  end

end

The before and after callbacks are just hooks that allow you to do something before or after the rendering of the model. The around callback has the added bonus of being passed a block. This means that you may choose to alter the structure of it as it is being rendered, or even bypass the as_api_response if need be.

For example, if you wanted to cache the model's api_response, and only generate the rendered response if the cached version does not exist, you could do something like:

def around_api_response(api_template)
  Rails.cache.fetch("api_response_#{self.class.to_s}_#{id}_#{api_template.to_s}", :expires_in => 1.hour) do
    yield
  end
end

Author: coneybeare