15

ActiveJob::SerializationError任何人都知道在尝试序列化对象时避免发生这种情况Date的干净方法Time吗?

到目前为止,我有两个解决方案是:

  • 加载参数时调用 Marshal/JSON/YAML dump,然后load返回作业(这很糟糕,因为我需要修补邮件程序作业)
  • 猴子补丁DateTime类的:

/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

这也很糟糕。有人有更好的解决方案吗?

4

1 回答 1

4

你真的需要序列化吗?如果它只是一个 Time/DateTime 对象,为什么不将参数编码并作为 Unix 时间戳原语发送?

>> 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

请注意,这将精确到一秒钟之内。如果您需要 100% 的准确度,您需要将时间转换为 Rational 并将分子和分母都作为参数传递,然后Time.at(Rational(numerator, denominator)在作业中调用。

>> 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
于 2016-03-30T05:23:20.137 回答