lib/lazy_mapper.rb in lazy_mapper-0.1.1 vs lib/lazy_mapper.rb in lazy_mapper-0.2.0
- old
+ new
@@ -1,9 +1,8 @@
require 'bigdecimal'
require 'bigdecimal/util'
require 'time'
-require 'active_support/core_ext/class/attribute'
##
# Wraps a JSON object and lazily maps its attributes to domain objects
# using either a set of default mappers (for Ruby's built-in types), or
# custom mappers specified by the client.
@@ -33,10 +32,19 @@
Time => Time.method(:iso8601),
Date => Date.method(:parse),
URI => URI.method(:parse)
}.freeze
+ def self.default_value_for type, value
+ default_values[type] = value
+ end
+
+ def self.default_values
+ @default_values ||= DEFAULT_VALUES
+ end
+
+
# Default values for primitive types
DEFAULT_VALUES = {
String => '',
Integer => 0,
Numeric => 0,
@@ -47,15 +55,24 @@
def self.mapper_for(type, mapper)
mappers[type] = mapper
end
- class_attribute :mappers
- self.mappers = {}
+ def self.mappers
+ @mappers ||= DEFAULT_MAPPINGS
+ end
- attr_reader :mappers
+ def self.inherited(klass)
+ klass.instance_variable_set IVAR[:mappers], self.mappers.dup
+ klass.instance_variable_set IVAR[:default_values], self.default_values.dup
+ end
+
+ def mappers
+ @mappers ||= self.class.mappers
+ end
+
IVAR = -> name {
name_as_str = name.to_s
if name_as_str[-1] == '?'
name_as_str = name_as_str[0...-1]
end
@@ -303,14 +320,14 @@
attr_writer :json
attr_writer :mappers
def mapping_for(name, type)
- mappers[name] || mappers[type] || self.class.mappers[type] || DEFAULT_MAPPINGS[type]
+ mappers[name] || mappers[type] || self.class.mappers[type]
end
def default_value(type)
- DEFAULT_VALUES.fetch(type) { nil }
+ self.class.default_values[type]
end
def mapped_value(name, unmapped_value, type, map: mapping_for(name, type), default: default_value(type))
if unmapped_value.nil?
# Duplicate to prevent accidental sharing between instances