lib/hashr.rb in hashr-0.0.11 vs lib/hashr.rb in hashr-0.0.12
- old
+ new
@@ -13,14 +13,23 @@
end
def definition
@definition ||= {}
end
+
+ def default(defaults)
+ @defaults = defaults
+ end
+
+ def defaults
+ @defaults ||= {}
+ end
end
def initialize(data = {}, definition = self.class.definition, &block)
- replace(deep_hashrize(definition.deep_merge((data || {}).deep_symbolize_keys)))
+ replace((deep_hashrize(definition.deep_merge((data || {}).deep_symbolize_keys))))
+ deep_defaultize(self)
(class << self; self; end).class_eval(&block) if block_given?
end
def []=(key, value)
super(key, value.is_a?(Hash) ? self.class.new(value, {}) : value)
@@ -44,23 +53,45 @@
def include_modules(modules)
Array(modules).each { |mod| meta_class.send(:include, mod) } if modules
end
+ def include_accessors(accessors)
+ Array(accessors).each { |accessor| meta_class.send(:define_method, accessor) { self[accessor] } } if accessors
+ end
+
def meta_class
class << self; self end
end
protected
def deep_hashrize(hash)
hash.inject(TEMPLATE.dup) do |result, (key, value)|
- if key.to_sym == :_include
+ case key.to_sym
+ when :_include
result.include_modules(value)
+ when :_access
+ result.include_accessors(value)
else
result.store(key.to_sym, value.is_a?(Hash) ? deep_hashrize(value) : value)
end
result
end
+ end
+
+ def deep_defaultize(hash)
+ self.class.defaults.each do |key, value|
+ case key.to_sym
+ when :_include
+ hash.include_modules(value)
+ when :_access
+ hash.include_accessors(value)
+ end
+ end
+ hash.each do |key, value|
+ deep_defaultize(value) if value.is_a?(Hash)
+ end
+ hash
end
end