简体   繁体   中英

Rails: Scope: making a method available to all Views and Controllers

I've struggled with scope for a few days. I would like to have a small number of methods available to ALL Views and Controllers. Suppose the code is:

def login_role
  if current_user
    return current_user.role
  end
  return nil
end

If I include it in application_helper.rb, then it's only available to all Views, but not available to all Controllers

If I include it in application_controller.rb, then it's available to all Controllers, but not available to all Views.

Use the helper_method method in your ApplicationController to give the views access.

class ApplicationController < ActionController::Base

  helper_method :login_role

  def login_role
    current_user ? current_user.role : nil
  end

end

Consider putting all the related methods in their own module then you may make them all available like this:

helper LoginMethods

Create your own library (it could have classes, modules, methods), and put it in the lib directory. Let's call it my_lib.rb.

In your application_controller.rb, and application_helper.rb add the following line:

require 'my_lib'

This will make all the classes, modules, methods available to all Views and Controllers

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