ActiveSupport::CurrentAttributes
What is Active Support?
Active Support is the Ruby on Rails component responsible for providing Ruby language extensions, utilities, and other transversal stuff.
What is ActiveSupport::CurrentAttributes
Abstract super class that provides a thread-isolated attributes singleton, which resets automatically before and after each request. This allows you to keep all the per-request attributes easily available to the whole system.
How to use it in your Rails APP?
first in your application_controller define a method called set_current_user. we put this method in application controller because all other controllers inhert from it
class ApplicationController < ActionController::Basebefore_action :set_current_user def set_current_user
if session[:user_id]
Current.user = User.find_by[id: session[:user_id]
end
end
end
before_action method in rails means before you run any actions in other controllers call first ‘set_current_user’ method. When you make request in your rails app ‘set_current_user’ method will check if the Current.user = nil (means user not logged in) or Current.user = “hashed string” (means user is logged in).
after that in app/model define Current model
class Current < ActiveSupport::CurrentAttributes
attribute :user
end
If you do not want to use ActiveSupport::CurrentAttributes class to check if user already logged in or not you can do the following in your Application controller
class ApplicationController < ActionController::Base
def home
if logged_in?
redirect_to user_path(current_user)
end
end def current_user
@current_user ||= User.find(session[:user_id])
if session[:user_id]
end def logged_in?
!!current_user
end def authenticate_user
if !logged_in?
redirect_to '/'
end
end
end
That’s all thank you for reading check out some of the cool functionality provided to you By Active Support