railstutorial.org has a suggestion which strikes me as a little odd.
It suggests this code:
class ApplicationController < ActionController::Base
protect_from_forgery
include SessionsHelper
end
The include SessionsHelper
makes the methods available from ApplicationController
, yes, but it makes them available in any view, as well. I understand that authentication/authorization is cross-cutting, but is this really the best place?
That seems to me to be potentially too broad of a scope. Putting code which implements, say, a before_filter
which conditionally redirects (as the railstutorial.org example does) in a module which more commonly contains view helpers seems surprising.
Would functionality not strictly needed in views be better placed in ApplicationController or elsewhere?
Or am I just thinking too much about this?
Indeed, your feeling is correct.
I would implement this the other way around: add the functions sign_in
and current_user
to ApplicationController
(or if you really want to: in a separate module defined in lib
and include it), and then make sure that the current_user
method is available in the view.
In short:
class ApplicationController
helper_method :current_user
def sign_in
end
def current_user
@current_user ||= user_from_remember_token
end
end
Of course, if you have a lot of code to place into your ApplicationController
it can get messy. In that case I would create a file lib\session_management.rb
:
module SessionManagement
def self.included(base)
base.helper_method :current_user
end
def sign_in
..
end
def current_user
..
end
end
and inside your controller you can then just write:
class ApplicationController
include SessionManagement
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With