I have a details page in Rails 3 app that has several instance variable. For example, my view has the following instances:
@product
@program
@action
...etc...
Some of them are single strings, some are arrays (result of requests from external APIs). Overall, the data comes from at least 3 models.
My question is: What is the best way to consolidate instance variables so my view and my controller look cleaner (without sacrificing readability)? I understand the question is open-ended and everyone has their own preferences, but what are some of the options? I am thinking along the lines of combining the instance variables into an object so the previous code becomes something like this:
Details.product
Details.program
Details.action
Thanks a lot!
UPDATE: Going the object route, is there any good examples (github, blog posts) of actually implementing it?
In my opinion the best way to clean up your controller actions is to assign as few instance variables as possible there. In practice, I try to only assign instance variables in the action/before_filters that are directly derived from the parameters passed to it. Also, in general I try to push as many instance variable assignments to before_filters as I can so as to keep the actions slim.
But the best way to cut down on instance variable assignment in the actions is to use view helpers. For instance if you are currently assigning an instance variable in an action which you use to output some div with, just use a view helper to do the output directly without any need to pass an object to the view.
Here's an example of a before_filter on a controller:
before_filter :assign_variables, :only => :show
def show; end
private
def assign_variables
@product = Product.find(params[:product_id])
@program = Program.find(params[:program_id])
@action = Action.find(params[:action_id])
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With