brandonhilkert / sucker_punch

Sucker Punch is a Ruby asynchronous processing library using concurrent-ruby, heavily influenced by Sidekiq and girl_friday.
MIT License
2.65k stars 114 forks source link

Capturing the environment #119

Closed grosser closed 9 years ago

grosser commented 9 years ago

I'd like to capture and restore the environment during job enqueue (I18n.local, Time.zone, Rails.logger.tags etc), is there any suggested way to do this ?

@brandonhilkert

FYI atm doing this:

class BackgroundJob
  include SuckerPunch::Job
  workers 2

  def perform(klass, id, method, environment)
    restore_environment(environment) do
      ActiveRecord::Base.connection_pool.with_connection do
        Timeout.timeout(30) do
          klass.find(id).public_send(method)
        end
      end
    end
  end

  # FYI: this does not work as instance method since it's already in another thread by then
  def self.enqueue(*args)
    args << capture_environment
    new.async.perform(*args)
  end

  private

  def self.capture_environment
    {
      tagged: Rails.logger.formatter.current_tags.dup
    }
  end

  def restore_environment(environment, &block)
    Rails.logger.tagged(*environment.fetch(:tagged), &block)
  end
end
brandonhilkert commented 9 years ago

I haven't experienced the need and haven't heard anyone else ask about it. Not opposed to it, but I'm sensitive to not adding too much Rails-related code to the codebase, since Sucker Punch works well with it. Might be a good opportunity for an extension gem.