Sha256: ee99e98075ed103c2fe057ebfb4028e80177de2ce3d166d0e38b08689a17e50b
Contents?: true
Size: 1.45 KB
Versions: 1
Compression:
Stored size: 1.45 KB
Contents
class Hashr < Hash autoload :EnvDefaults, 'hashr/env_defaults' TEMPLATE = new class << self attr_accessor :raise_missing_keys def define(definition) @definition = definition end def definition @definition ||= {} end end def initialize(data = {}) include_modules(data.delete(:_include)) if data replace(deep_hasherize(deep_merge(self.class.definition, data))) end def []=(key, value) super(key, value.is_a?(Hash) ? self.class.new(value) : value) end def respond_to?(name) true end def method_missing(name, *args, &block) case name.to_s[-1, 1] when '?' !!self[name.to_s[0..-2].to_sym] when '=' self[name.to_s[0..-2].to_sym] = args.first else raise(IndexError.new("Key #{name.inspect} is not defined.")) if !key?(name) && self.class.raise_missing_keys self[name] end end protected def include_modules(modules) Array(modules).each { |mod| meta_class.send(:include, mod) } if modules end def meta_class class << self; self end end def deep_merge(left, right) merger = proc { |key, v1, v2| v1.is_a?(Hash) && v2.is_a?(Hash) ? self.class.new(v1.merge(v2, &merger)) : v2 } left.merge(right || {}, &merger) end def deep_hasherize(hash) hash.inject(TEMPLATE.dup) do |result, (key, value)| result[key.to_sym] = value.is_a?(Hash) ? deep_hasherize(value) : value result end end end
Version data entries
1 entries across 1 versions & 1 rubygems
Version | Path |
---|---|
hashr-0.0.6 | lib/hashr.rb |