Instantly share code, notes, and snippets.

Embed
What would you like to do?
Current user concern used in various Ruby on Rails projects
module CurrentUser
extend ActiveSupport::Concern
included do
helper_method :current_user
end
def current_user
return @current_user if defined?(@current_user)
@current_user = User.find_by(id: session[:id])
end
def sign_in(user)
user_id = user.respond_to?(:id) ? user.id : user
session[:id] = user_id
end
def sign_out
session[:id] = nil
cookies[:auth_token] = nil
end
def require_user
redirect_to user_not_required_path, notice: "You must be logged in to access this page" if current_user.blank?
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment