【问题标题】:Merging a Hash to Hash Child Class - Ensure nested hash has the Child Class properties将哈希合并到哈希子类 - 确保嵌套哈希具有子类属性
【发布时间】:2012-09-26 10:58:54
【问题描述】:

我有一个哈希子类,我通常想从另一个哈希初始化它的数据并使用它:

class ValidatedJson < Hash
    @schema = {}
    def initialize(hash = {})
        super
        JSON::Validator.validate!(@schema, hash, :validate_schema => true)
        self.update(hash)
    end

    def [](key)
        self.fetch(key)
    end
end

但是,单独使用 self.update 时,任何嵌套哈希都将是 Hash 类型,而不是具有我的子类 ValidatedJson 的属性。有人知道确保这一点的快速有效方法吗?

【问题讨论】:

  • 递归转换嵌入的哈希可能是你能做的最好的。
  • 是的,这就是我最终做的......

标签: ruby inheritance hash


【解决方案1】:

我可能会效仿 ActiveSupport 的 HashWithIndifferentAccess 所做的,即覆盖 update() 以及构造函数。

请参阅 https://github.com/rails/rails/blob/master/activesupport/lib/active_support/hash_with_indifferent_access.rb 了解它们的实施。

【讨论】:

  • 这又出现了,我们将更深入地研究 HashWithIndiffergentAccess。谢谢!
猜你喜欢
  • 1970-01-01
  • 2020-12-08
  • 2019-02-21
  • 2019-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多