module Sidekiq::CurrentAttributes

Automatically save and load any current attributes in the execution context so context attributes “flow” from Rails actions into any associated jobs. This can be useful for multi-tenancy, i18n locale, timezone, any implicit per-request attribute. See ActiveSupport::CurrentAttributes.

For multiple current attributes, pass an array of current attributes.

@example

# in your initializer
require "sidekiq/middleware/current_attributes"
Sidekiq::CurrentAttributes.persist("Myapp::Current")
# or multiple current attributes
Sidekiq::CurrentAttributes.persist(["Myapp::Current", "Myapp::OtherCurrent"])

Public Class Methods

persist(klass_or_array, config = Sidekiq.default_configuration) click to toggle source
# File lib/sidekiq/middleware/current_attributes.rb, line 102
def persist(klass_or_array, config = Sidekiq.default_configuration)
  cattrs = build_cattrs_hash(klass_or_array)

  config.client_middleware.add Save, cattrs
  config.server_middleware.prepend Load, cattrs
end

Private Class Methods

build_cattrs_hash(klass_or_array) click to toggle source
# File lib/sidekiq/middleware/current_attributes.rb, line 111
def build_cattrs_hash(klass_or_array)
  if klass_or_array.is_a?(Array)
    {}.tap do |hash|
      klass_or_array.each_with_index do |klass, index|
        hash[key_at(index)] = klass.to_s
      end
    end
  else
    {key_at(0) => klass_or_array.to_s}
  end
end
key_at(index) click to toggle source
# File lib/sidekiq/middleware/current_attributes.rb, line 123
def key_at(index)
  (index == 0) ? "cattr" : "cattr_#{index}"
end