A
A
Askhat Bikmetov2015-04-06 12:12:51
Ruby on Rails
Askhat Bikmetov, 2015-04-06 12:12:51

How to write to the database inside the background worker?

I am developing a small utility in Ruby. Its two main tasks are: periodically executing an HTTP request with saving the response in the database and displaying the received data in the web interface.
As tools I chose:

  • Sinatra - for web interface
  • Mongoid - for date mapping
  • Sidekiq - background task

And if everything is very clear with the first, then difficulties begin with the last two. It is impossible to access the model inside the worker class descriptor (due to the unitialized constant AwesomeWorker::AwesomeModel , passing a model instance as an argument to the worker is also problematic because Sidekiq casts all arguments to String . I did a small workaround by passing the freshly created object_id as an argument to the worker model, and inside the worker I again get an instance of the model using ObjectSpace ._id2ref but this is some kind of dirty hack (does not work yet):
require 'sidekiq'
require 'awesome_model'
class AwesomeWorker
  include Sidekiq::Worker
  def perform model_id
    model = ObjectSpace._id2ref model_id
    model.update_attributes! { data_key: "data value" }
  end
end
AwesomeWorker.perform_async AwesomeModel.new.object_id.to_i

Why is it so important for me to invoke a model from a worker? Because the call is initiated not by the controller, but by time.
Did I choose the right tools? What am I doing wrong? How would you solve such a problem?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Viktor Vsk, 2015-04-06
@askhat

The error is elementary and is not associated with any of the listed tools.
What to do?

require 'sidekiq'
require 'awesome_model'
AwesomeModel # => ???
...

If not ok, see why your model is not loading.
If ok then:
two colons in front of a class or module make you look for it (class or module) not in the current context (module), but from the very beginning (from Object) . But really, it's unlikely.
PS
I would take Resque for this:
1. I never had any problems, it started right away
2. The process is born and dies (when there is a plus, when there is a minus. In my case, it was a plus, because the process in work became very fat and was not unloaded into in the case of DJ or Sidekiq, and in Resque it would finish work, die and release memory)
3. Supported by github and heroku

N
Nikolai Markov, 2015-04-06
@manameiz

It would be nice to show the file 'awesome_model'.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question