Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SerializationError Rails ActiveJob Time and Date

Anyone know of a clean way to avoid the ActiveJob::SerializationError that occurs when trying to serialize a Date or Time object?

The two solutions I've had so far are to:

  • Call Marshal/JSON/YAML dump when loading the arguments and then load back in the Job (which sucks because I need to monkey patch the mailer job)
  • Monkey patch Date and Time like so:

/lib/core_ext/time.rb

class Time

  include GlobalID::Identification

  def id
    self.to_i
  end

  def self.find(id)
    self.at(id.to_i)
  end
end

/lib/core_ext/date.rb

class Date

  include GlobalID::Identification

  def id
    self.to_time.id
  end

  def self.find(id)
    Time.find(id).to_date
  end
end

Which also sucks. Anyone have a better solution?

like image 833
kddeisz Avatar asked Apr 16 '15 19:04

kddeisz


1 Answers

Do you really need serialization? If it's just a Time/DateTime object, why not just encode and send your parameter as a Unix timestamp primitive?

>> tick = Time.now
=> 2016-03-30 01:19:52 -0400

>> tick_unix = tick.to_i
=> 1459315192

# Send tick_unix as the param...

>> tock = Time.at(tick_unix)
=> 2016-03-30 01:19:52 -0400

Note this will be accurate to within one second. If you need 100% exact accuracy you'll need to convert the time to a Rational and pass both the numerator and denominator as params and then call Time.at(Rational(numerator, denominator) within the job.

>> tick = Time.now
=> 2016-03-30 01:39:10 -0400

>> tick_rational = tick.to_r
=> (1459316350224979/1000000)

>> numerator_param = tick_rational.numerator
=> 1459316350224979

>> denominator_param = tick_rational.denominator
=> 1000000

# On the other side of the pipe...

>> tock = Time.at(Rational(numerator_param, denominator_param))
=> 2016-03-30 01:39:10 -0400

>> tick == tock
=> true
like image 177
Anthony E Avatar answered Nov 19 '22 18:11

Anthony E