lib/config_mapper.rb in config_mapper-0.1.0 vs lib/config_mapper.rb in config_mapper-0.2.0
- old
+ new
@@ -17,11 +17,11 @@
mapper.set_attributes(data)
mapper.errors
end
def initialize(target, errors = {})
- @target = target
+ @target = ObjectAsHash[target]
@errors = errors
end
attr_reader :target
attr_reader :errors
@@ -37,25 +37,46 @@
private
# Set a single attribute.
#
def set_attribute(key, value)
- if value.is_a?(Hash)
- set_nested(key, value)
+ if value.is_a?(Hash) && !target[key].nil?
+ nested_errors = ErrorProxy.new(errors, "#{key}.")
+ nested_mapper = self.class.new(target[key], nested_errors)
+ nested_mapper.set_attributes(value)
else
- target.public_send("#{key}=", value)
+ target[key] = value
end
rescue NoMethodError, ArgumentError => e
errors[key] = e
end
- def set_nested(key, value)
- nested_target = target.public_send(key)
- nested_errors = ErrorProxy.new(errors, "#{key}.")
- nested_mapper = self.class.new(nested_target, nested_errors)
- nested_mapper.set_attributes(value)
+ class ObjectAsHash
+
+ def self.[](target)
+ if target.is_a?(Hash)
+ target
+ else
+ ObjectAsHash.new(target)
+ end
+ end
+
+ def initialize(target)
+ @target = target
+ end
+
+ def [](key)
+ @target.public_send(key)
+ end
+
+ def []=(key, value)
+ @target.public_send("#{key}=", value)
+ end
+
end
+ # Wraps a Hash of errors, injecting prefixes
+ #
class ErrorProxy
def initialize(errors, prefix)
@errors = errors
@prefix = prefix