Wednesday, February 6, 2013

Initialize Instance Variables Needed By A View In One Place

In Rails, should Controller#create fail, the pre-generated code will call render :action => "new". But all too often rendering the new view requires other instance variables to be assigned, which don't get assigned in this execution path if I place the initialization code in the Controller#new method.

I have been frustrated by the lack of a good way to handle it. At first I looked into the presenter pattern, but did not come up with anything that I liked.

Then, I came across this idea, which at first glance, seems to work well. My main goal is to have a good place to initialize the needed instance variables needed by the view only once, and overriding #render seems like a good way to go.

Your thoughts?
# Override this method so that we can initialize the needed
# instance variables the view needs all in one place

def render(*args)
  action = args[0][:action] || action_name
  case action
  when "new"
    @accounts = Account.order(:name)
    ...
  end
end

No comments: