简体   繁体   中英

Are methods in controller after helper_method available to all views in rails

For protected methods in rails controllers, they are made available to its view by declaring them with helper_method. By default, methods in rails helper to views are shared (accessible) in all views. My question is, are the controller methods declaring with helper_method shared (accessible) by all views as well?

Thanks

If you declare a controller method as a helper with the helper_method, then the helper will be available only in the views belonging to the controller.

If you want to make the helper available accross all views, you have to define the controller method, and declare the helper, in the Application controller.

If you are interested, this is the relevant Rails code:

def helper_method(*meths)
  meths.flatten!
  self._helper_methods += meths

  meths.each do |meth|
    _helpers.class_eval <<-ruby_eval, __FILE__, __LINE__ + 1
      def #{meth}(*args, &blk)
        controller.send(%(#{meth}), *args, &blk)
      end
    ruby_eval
  end
end

You can see that when called, the helper just calls a method of the same name on the controller.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM