加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 19:35:56 所属栏目:百科 来源:网络整理
导读:任何人知道一个干净的方法来避免在尝试序列化Date或Time对象时发生的ActiveJob :: SerializationError? 我迄今为止所做的两个解决方案是: 在加载参数时调用元帅/ JSON / YAML转储,然后加载到Job中(因为我需要猴子补丁邮件作业) 猴子补丁日期和时间如此: /
任何人知道一个干净的方法来避免在尝试序列化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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读