有人知道在尝试序列化 Date
或 Time
对象时避免发生 ActiveJob::SerializationError
的干净方法吗?
到目前为止,我有两个解决方案:
- 在加载参数时调用 Marshal/JSON/YAML
dump
然后load
回到作业中(这很糟糕,因为我需要猴子修补邮件作业)< - 猴子补丁
Date
和Time
像这样:
/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(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
关于ruby-on-rails - SerializationError Rails ActiveJob 时间和日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29683846/