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

前端 未结 4 1336
眼角桃花
眼角桃花 2020-11-29 17:22

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?

4条回答
  •  再見小時候
    2020-11-29 17:54

    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
    

提交回复
热议问题