author avatar

giritharan

Mon Oct 21 2024

Managing Global Attributes with ActiveSupport::CurrentAttributes in Rails

In 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*:



class Current < ActiveSupport::CurrentAttributes
  attribute :user, :account, :request_id
end


app/jobs/my_job.rb:



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
end


In 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