Search code examples
ruby-on-railsrubysidekiq

How can I find() a resource passed to a sidekiq worker?


Basically, I have a block of code that needs to be executed inside a sidekiq worker, which will interact over a resource passed as argument (maybe). This resource is a Rails model.

Differently from other questions on SO related to passing arguments to a worker, here I don't know if it will be a User or a House model. So I can't simply use MyWorker.perform(user_id), since I don't know which model id I'll be passing as argument.

Also, I read that I can't simply expect to pass my model object to a sidekiq worker and receive it on the other side, once it'll transform it to json.

So what I had in mind, was something like this:

# somewhere_in_my_code.rb

MyWorker.perform(resource.id, resource_model) # still don't know what this resource_model would be

# my_worker.rb

def perform(resource_id, resource_model)
  model = some_magic_method_to_return_a_model(resource_model)
  resource = model.find(resource_id)

  # do what I have to do with the resource found
end

But I really don't know if this some_magic_method_to_return_a_model exists. Or if that's even possible. Anyway, any help will be appreciated, thanks!

NOTE: I'm using Ruby 2.4.8, Rails 4.1.10, Sidekiq 4.1.0


Solution

  • It does. Let's assume you have a User model:

    > user = User.last
    > id = user.id
    > model_name = user.model_name.name
    > model_name.safe_constantize.find(id)
    > model_name.safe_constantize.find(id) == user
    => true
    

    This is basically how polymorphic associations work in Rails.