- Published
- Author
- GiritharanSystem Analyst
Managing Global Attributes with
In Rails,
In controllers, Rails automatically resets
Code Example:
In summary: Rails handles resetting
#current #currentAttributes #CU6U0R822
ActiveSupport::CurrentAttributes in RailsIn Rails,
ActiveSupport::CurrentAttributes simplifies the process of storing global, thread-safe data like Current.user or Current.account during requests or jobs. It should be limited to top-level globals, such as user and request details, which are needed across all actions.In controllers, Rails automatically resets
Current between requests, so we don’t need to manually clear it. However, In Active Jobs, we need to manually reset Current after each job to prevent data from leaking between job executions. We achieve this using the after_perform callback.Code Example:
*app/models/current.rb*:Code
class Current < ActiveSupport::CurrentAttributes
attribute :user, :account, :request_id
endapp/jobs/my_job.rb:Code
class MyJob < ApplicationJob
after_perform :clear_current_attributes
def perform(params)
set_current_attributes(params[:user_id])
end
private
def set_current_attributes(user_id)
Current.user = User.find_by(id: user_id)
Current.request_id = SecureRandom.uuid
end
def clear_current_attributes
Current.reset
end
endIn summary: Rails handles resetting
Current for controllers, but for jobs, we must manually reset it after each job to avoid data leakage.#current #currentAttributes #CU6U0R822