I have a problem that when I pass some Date
objects as arguments to different methods, they turn into String
.
In my Rails app, there is a service that calls a Sidekiq worker to execute a method in a model.
When the service object is initialized, it has Date
instance methods. I have confirmed their types using debugger.
It passes the instance methods to a Sidekiq worker using perform_async
. The perform
method is Sidekiq is a one line method that invokes a method in a model, passing arguments it received from the service to the model.
In the model side, the argument passed in from the Sidekiq worker is no longer a Date
type. They are String
(e.g. "2015-01-20"). I have confirmed this using degugger.
Any thoughts on why this is happening?
When you call the perform_async
method on a Sidekiq worker, the provided arguments are translated into JSON so that they can be stored in the Redis queue that Sidekiq background workers pull from, and then translated back to primitive types from JSON to be passed to perform
in the background worker process. Because of this, it's best to pass simple arguments to your Sidekiq workers; in fact, it's a best practice.
For your specific problem, you could take the date passed into the perform method of your worker and use Date.parse(date_string)
to turn it back into a Date
object. In this case, you might also want to call to_s
on the argument to perform_async
, just to make it obvious to any later readers of your code that what is passed to perform
is a string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With