Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are all Rails helpers available to all views, all the time? Is there a way to disable this?

Why can I access helper methods for one controller in the views for a different controller? Is there a way to disable this without hacking/patching Rails?

like image 266
Nate Smith Avatar asked Jul 24 '09 19:07

Nate Smith


People also ask

What are view helpers in Rails?

A helper is a method that is (mostly) used in your Rails views to share reusable code. Rails comes with a set of built-in helper methods. One of these built-in helpers is time_ago_in_words . This method is helpful whenever you want to display time in this specific format.

When should you use helpers Rails?

Basically helpers in Rails are used to extract complex logic out of the view so that you can organize your code better. I've seen two benefits for using helpers in my experience so far: Extract some complexity out of the view. Make view logic easier to test.

Where are custom view helpers Rails?

Custom HelpersEdit Custom helpers for your application should be located in the app/helpers directory.

Can we use helper method in controller Rails?

In Rails 5, by using the new instance level helpers method in the controller, we can access helper methods in controllers.


2 Answers

@George Schreiber's method doesn't work as of Rails 3.1; the code has changed significantly.

However, there's now an even better way to disable this feature in Rails 3.1 (and hopefully later). In your config/application.rb, add this line:

config.action_controller.include_all_helpers = false 

This will prevent ApplicationController from loading all of the helpers.

(For anyone who is interested, here's the pull request where the feature was created.)

like image 140
Craig Walker Avatar answered Sep 25 '22 10:09

Craig Walker


The answer depends on the Rails version.

Rails >= 3.1

Change the include_all_helpers config to false in any environment where you want to apply the configuration. If you want the config to apply to all environments, change it in application.rb.

config.action_controller.include_all_helpers = false 

When false, it will skip the inclusion.

Rails < 3.1

Delete the following line from ApplicationController

helper :all 

In this way each controller will load its own helpers.

like image 22
Simone Carletti Avatar answered Sep 24 '22 10:09

Simone Carletti