Reputation: 6639
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.
Upvotes: 7
Views: 5283
Reputation: 2048
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
Upvotes: 31
Reputation: 6639
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
Upvotes: -4