IdolHands.com :: Days in the Life of an Alpha Geek
If you're a Rails developer, you've probably seen this line a thousand times near the top of your generated application.rb file, but do you know what it really means?
helper :all
Here's a demonstration. Let's say that in helpers/application_helper.rb, you have a method like this:
def helper_test "This is from the application helper." end
For the sake of argument, say that you use this method in your layout file. (In the real-world experience that lead to my learning about this, the code in question was a fairly complicated breadcrumb generation method that I did not want to further clutter with more conditionals.)
You decide that what helper_test returns is great for most cases, but you want to do something different for pages in /foo. Since your layout file is calling helper_test, and you want to keep logic out of your layout file, you decide to add a method with the same name but different logic to helpers/foo_helper.rb:
def helper_test "This is from the foo helper." end
Now, you might expect that the helper_test would be automatically scoped to the foo controller, and if you requested a page in /views/foo/, it would appear that you are right: you see "This is from the foo helper." displayed in your layout. But if you traverse your site and go to another set of pages, you'll see that the helper_test method from your foo_helper.rb has taken over the place. Rather than being scoped to the controller as you might expect from the naming convention, you've actually replaced the method that was defined in application_helper.rb.
The reason this happens goes back to that one line in your application.rb file:
helper :all
What this is actually saying is that any controller that extends application.rb— which is to say, all of your controllers— gets access to every other helper module's methods. Because of their loading order, the last method defined will clobber any previously defined methods with the same name. Making helper methods accessible across the helper modules is inherently useful, but only as long as you realize what's going on.
If you don't want this behaviour, either comment out helper :all, or take care to give your helper methods unique names.
In short, conventions are great, but only if you know what they are actually doing.