Sunday, February 17, 2013

Controller#pre_render

As a follow-up to a previous post about Initialize Instance Variables Needed By A View In One Place, here is a more evolved/elegant approach.

First, I override the render method in app/controllers/application_controller.rb:

# override render so we can call pre_render on child classes

def render(*args)
  if self.class.method_defined? :pre_render
    action = args[0].is_a?(Hash) ? (args[0][:action] || action_name) : action_name
    self.pre_render(action.to_sym)
  end
  super
end

Then, I optionally define the pre_render method in my other controllers:

# define this method so that we can initialize the needed instance
# variables the views need all in one place

def pre_render(action)
  case action
  when :edit, :new
    @users = User.all
  when :show
    @subaccounts = @account.subaccounts.order(:name)
  end
end
Conceptually, this is similar to ASP.NET's PreRender() event handler.

No comments: