将哈希值合并到哈希子类 - 确保嵌套哈希具有子类属性

时间:2012-09-13 20:44:51

标签: ruby inheritance hash

我有一个Hash Child Class,我通常希望从另一个Hash初始化其数据并使用它:

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的属性。任何人都知道一种快速有效的方法来确保这一点吗?

1 个答案:

答案 0 :(得分:2)

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

请参阅https://github.com/rails/rails/blob/master/activesupport/lib/active_support/hash_with_indifferent_access.rb了解其实施情况。