Reputation: 712
I have a Hash Child Class where I typically want to initialize its data from another Hash and used this:
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
However, with self.update alone, any nested hash would be of type Hash, rather than having the properties of my child class ValidatedJson. Anyone know of a quick efficient way of ensuring this?
Upvotes: 2
Views: 303
Reputation: 917
I'd probably emulate what ActiveSupport's HashWithIndifferentAccess
does, which is to override update()
as well as the constructor.
See https://github.com/rails/rails/blob/master/activesupport/lib/active_support/hash_with_indifferent_access.rb for their implementation.
Upvotes: 2