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

Possible to save information in job instance variable? #214

Closed anirbanmu closed 6 years ago

anirbanmu commented 6 years ago

I was wondering if it's possible to re-use something like a per-thread session instance variable in my job class in order to save having to create a new one each time. All I want to do is have one session per thread used; it does not matter what session my job is using as long as it's not the same as another concurrent thread. I'm not sure if I'm doing a good job explaining this. Let me know if it's unclear.

anirbanmu commented 6 years ago

It seems I can do something like this:

@@session = Concurrent::ThreadLocalVar.new(nil)

def perform(comment_id, comment_body)
  @@session.value ||= Object.new
  print @@session.value
end

Anything wrong with this approach?

brandonhilkert commented 6 years ago

That should work. I reach for this on the web side when I need something similar: https://github.com/steveklabnik/request_store. It's probably worth digging through there to compare the approaches.