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

僤鯓⒐⒋嵵緔 提交于 2019-11-27 02:45:22

@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.)

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.

George Schreiber

In Rails 3, actioncontroller/base.rb (around line 224):

def self.inherited(klass)
  super
  klass.helper :all if klass.superclass == ActionController::Base
end

So yes, if you derive your class from ActionController::Base, all helpers will be included.

To come around this, call clear_helpers (AbstractClass::Helpers; included in ActionController::Base) at the beginning of your controller's code. Source code comment for clear_helpers:

# Clears up all existing helpers in this class, only keeping the helper
# with the same name as this class.

E.g.:

class ApplicationController < ActionController::Base
  clear_helpers
  ...
end

Actually in Rails 2, the default functionality of ActionController::Base was to include all helpers.

Changeset 6222 on 02/24/07 20:33:47 (3 years ago) by dhh: Make it a default assumption that you want all helpers, all the time (yeah, yeah)

change:

class ApplicationController < ActionController::Base 
  helper :all # include all helpers, all the time 
end 

As of Rails 3 beta 1, that is no longer the case as noted in the CHANGELOG:

  • Added that ActionController::Base now does helper :all instead of relying on the default ApplicationController in Rails to do it [DHH]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!