Reputation: 8630
I'm wondering if there's a specific programming principle (Demeter?) that supports the idea that Rails helpers should never use controller instance variables, rather, they should receive such variables as function parameters. For example, assume my ChickensController#squawk
action creates an instance variable called @egg
. Furthermore, assume the squawk
view contains a call to a helper called cockadoodledoo
, implemented like so:
def cockadoodledoo
@egg.to_s
end
Would it be better or unnecessarily verbose to pass @egg
as a parameter, such that the view calls cockadoodledoo(@egg)
and for the helper to resemble:
def cockadoodledoo(egg)
egg.to_s
end
I hope one of you happy hackers is bored enough on a Friday afternoon to assert an answer. Cockadoodledoo!
This question here is similar, but was never accurately answered.
Upvotes: 40
Views: 7747
Reputation: 17512
Receive them as a param. Otherwise, as the app grows, it gets very difficult to trace where the instance vars are being set when refactoring, troubleshooting, etc.
Also, I believe there's a general best practice to only use instance vars in views within the initial template...and from there you should pass the var into helpers and other partials.
Upvotes: 35
Reputation: 434665
I don't know if there is any named principle governing this sort of thing but I would pass an argument. Not only will the argument make your helper easier to test and your application's data flow easier to follow but it will also let you use one helper for a single instance as well as a list; if you pass an argument then both:
<%= cockadoodledoo @egg %>
and:
<% @eggs.each do |egg| %>
<%= cockadoodledoo egg %>
<% end %>
will work as expected without introducing a special cockadoodledoo
that handles a list in @eggs
rather than a single @egg
.
Upvotes: 12
Reputation: 25270
Since helper messages are mixed in to all controllers, hence available to all views (including partials and layouts), it's always wise to establish a clear contract - the parameters.
The only exception I could think of is when a instance variable is also available to all views and controllers, like a menu or something similar.
Upvotes: 8
Reputation: 115521
I'd say you should always pass the variables explicitly to your helper for 2 reasons:
you control exactly what you do
above all, you can test your helper
Upvotes: 21