【问题标题】:SerializationError Rails ActiveJob Time and DateSerializationError Rails ActiveJob 时间和日期
【发布时间】:2015-06-23 09:33:42
【问题描述】:

有人知道在尝试序列化DateTime 对象时避免出现ActiveJob::SerializationError 的干净方法吗?

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

  • 在加载参数时调用 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

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

【问题讨论】:

  • 真的有必要只将日期或时间传递给工作(以及为什么)?我认为最好将 ActiveModel 作为参数传递给作业,可能包含 Date 或 Time 实例。 (ActiveModel 包含 GlobalID::Identification,因此它们是可序列化的)
  • 不,没有必要。这只是方便。最重要的是,在我们集成 ActiveJob 之前,它与 DelayedJob 一起工作。所以......看起来很愚蠢,我需要更改我的代码才能与简单地应该抽象而不是更改功能的东西集成。
  • 您只将日期/时间对象加入队列?没有其他的? AFAIK,ActiveJob 实际上调用 Marshal 来序列化您的对象,并且需要类似于您所说的猴子补丁之类的东西,以便以后能够检索和调用该对象。你能发布你的邮件吗?
  • 你能举个例子说明你是如何排队的吗?

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


【解决方案1】:

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

【讨论】:

  • 我知道有很多方法可以通过改变值来做到这一点,我只是想知道是否有办法结合其他对象的序列化来做到这一点。就像能够通过my_method(date, time, model) 并让它工作一样。在这一点上,它已经过时了,因为这个问题是大约一年前提出的。
猜你喜欢
  • 2017-04-15
  • 2017-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多