【问题标题】:YAML, delayed_job : Psych vs Syck. How to make pysch read attr_accessors for a ruby objectYAML,delayed_job:Psych 与 Syck。如何让 pysch 读取 ruby​​ 对象的 attr_accessors
【发布时间】:2012-10-29 16:31:45
【问题描述】:

我在使用带 ruby​​ 1.9.3 的延迟作业 (3.0.3) 时遇到问题。以前我们使用的是 ruby​​ 1.8.7,它带有 yaml syck 解析器,它读取为 ruby​​ 对象设置的所有属性(包括 attr_accessors),但升级到 1.9.3 后,yaml 解析器切换到 psych(重新写)并且它不考虑除数据库中持久化的属性之外的任何属性。我们如何让心理也考虑到 attr_accessors。我试图切换到 syck thru:

YAML::ENGINE.yamler = 'syck'

但还是不行。

有人可以解决这个问题吗?

【问题讨论】:

    标签: yaml ruby-1.9.3 psych syck


    【解决方案1】:

    上面的 hack 不起作用,但我们只需要覆盖 ActiveRecord::Base 的 encode_with 和 init_with 方法以包含属性访问器。更准确地说,我们需要使用 att_accessors 设置编码器哈希,这会处理实例变量的持久性。

    有趣的阅读:https://gist.github.com/3011499

    【讨论】:

      【解决方案2】:

      delayed_job 反序列化器不会在加载的 ActiveRecord 对象上调用 init_with。

      这是延迟作业的猴子补丁,它确实在结果对象上调用 init_with:https://gist.github.com/4158475

      例如,对于那个猴子补丁,如果我有一个名为 Artwork 的模型,具有额外的属性路径和深度:

      class Artwork < ActiveRecord::Base
        def encode_with(coder)
          super
      
          coder['attributes']['path'] = self['path']
          coder['attributes']['depth'] = self['depth']
        end
      
        def init_with(coder)
          super
      
          if coder['attributes'].has_key? 'path'
            self['path'] = coder['attributes']['path']
          end
      
          if coder['attributes'].has_key? 'depth'
            self['depth'] = coder['attributes']['depth']
          end
      
          self
        end
      end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-26
        • 1970-01-01
        • 2015-12-30
        • 1970-01-01
        • 1970-01-01
        • 2011-10-15
        相关资源
        最近更新 更多