SerializationError Rails ActiveJob时间和日期

时间:2015-04-16 19:06:27

标签: ruby-on-rails ruby ruby-on-rails-4 rails-activejob

任何人都知道在尝试序列化ActiveJob::SerializationErrorDate对象时避免出现Time的干净方法吗?

到目前为止,我已经解决了两个问题:

  • 在加载参数时调用Marshal / JSON / YAML dump,然后在作业中调用load(这很糟糕,因为我需要修补邮件工作)
  • Monkey patch 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

哪个也很糟糕。任何人都有更好的解决方案吗?

1 个答案:

答案 0 :(得分:3)

你真的需要序列化吗?如果它只是一个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