Home > database >  How to properly pass "request" params in ActiveJob rails?
How to properly pass "request" params in ActiveJob rails?

Time:04-29

I would like to pass on the request params so that I can execute it on the delayed_job as follows:

ObserveJob.perform_later(request)

but the error is always ActiveJob::SerializationError: Unsupported argument type: ActionDispatch::Request

Is there a way to pass on this built-in request params in rails so it will execute properly using delayed_job?

CodePudding user response:

There can many ways one could be :

Delayed::Job.enqueue(Abc.new(param1, param2, queue: "Update Derive")

Delayed job will be like:

class Abc < Struct.new(:param1, :param2)
  def perform
    sum = param1   param2
    ...
  end
end

CodePudding user response:

Instead of passing the whole request object – which is quite big and complex – only pass the attributes you actually need to the job. This has several advantages:

  • Huge, complex, and nested objects, like request in your question, are hard to serialize or might not even support serialization at all.
  • Simple objects of very "basic" classes, like numbers or strings, are easier to serialize and require less memory in their serialized representation which ultimately makes your jobs faster.
  • Passing a complex object to a job that only needs certain attributes adds an unnecessary dependency to the request to the job. The job needs to know how the request object works and how to get the required attributes from that object.
  • Passing simple objects to a method makes testing easier because you do not need to build the complex thing to be able to test the method.

I would change the perform method to

def perform(path:, referer:, url: remote_ip:, user_agent:, location:)
  # ...
end

and call it like this:

ObserveJob.perform_later(
  path:       request.path,
  referer:    request.referer,
  url:        request.url,
  remote_ip:  request.remote_ip,
  user_agent: request.user_agent,
  location:   request.location
)
  • Related