ruby-on-rails – SerializationError Rails ActiveJob时间和日期

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – SerializationError Rails ActiveJob时间和日期前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
任何人知道一个干净的方法来避免在尝试序列化Date或Time对象时发生的ActiveJob :: SerializationError?

我迄今为止所做的两个解决方案是:

>在加载参数时调用元帅/ JSON / YAML转储,然后加载到Job中(因为我需要猴子补丁邮件作业)
猴子补丁日期和时间如此:

/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

哪个也很烂.任何人都有更好的解决方案?

解决方法

你真的需要序列化吗?如果它只是一个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(分子,分母)).

>> 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
原文链接:https://www.f2er.com/ruby/271456.html

猜你在找的Ruby相关文章