Last active
December 21, 2015 20:29
-
-
Save vincent178/6361714 to your computer and use it in GitHub Desktop.
module add helper methods, can use in view and controller
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Authentication | |
# Add helper method as soon as module included | |
def self.included(controller) | |
controller.send :helper_method, :current_user, :logged_in?, :redirect_to_target_or_default | |
end | |
def current_user | |
@current_user ||= User.find(session[:user_id]) if session[:user_id] | |
end | |
def logged_in? | |
current_user | |
end | |
def login_required | |
unless logged_in? | |
flash[:error] = "You must first log in or sign up before accessing this page." | |
store_target_location | |
redirect_to login_url | |
end | |
end | |
def redirect_to_target_or_default(default) | |
redirect_to(session[:return_to] || default) | |
session[:return_to] = nil | |
end | |
private | |
def store_target_location | |
session[:return_to] = request.request_uri | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment