Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 654
EastsideDev Avatar asked Jul 02 '12 13:07

EastsideDev


1 Answers

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

like image 57
Dean Brundage Avatar answered Oct 12 '22 22:10

Dean Brundage