Module: LightMapper::Helper
- Defined in:
- lib/light_mapper.rb
Class Method Summary collapse
- .array_key_extractor(object, current, full_path, strict, _any_keys) ⇒ Object
- .hash_key_extractor(object, current, full_path, strict, any_keys) ⇒ Object
- .key_destructor(value) ⇒ Object
- .raise_key_missing(current, full_path, additional_message = nil) ⇒ Object
- .value_extractor(object, current, path, full_path, strict = false, any_keys = false) ⇒ Object
Class Method Details
.array_key_extractor(object, current, full_path, strict, _any_keys) ⇒ Object
49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
# File 'lib/light_mapper.rb', line 49 def self.array_key_extractor(object, current, full_path, strict, _any_keys) index = current.to_s.match(/^(\d)+$/) ? current.to_i : nil if index raise_key_missing(current, full_path) if strict && index && object.size < index.next object[index] else method_name = current.to_s.to_sym raise_key_missing(current, full_path, "Array do not respond on #{method_name}") if strict && !object.respond_to?(method_name) object.public_send(method_name) end end |
.hash_key_extractor(object, current, full_path, strict, any_keys) ⇒ Object
42 43 44 45 46 47 |
# File 'lib/light_mapper.rb', line 42 def self.hash_key_extractor(object, current, full_path, strict, any_keys) keys = any_keys ? [current, current.to_s, current.to_s.to_sym] : [current] raise_key_missing(current, full_path) if strict && !keys.any? { |k| object.key?(k) } object.values_at(*keys).compact.first end |
.key_destructor(value) ⇒ Object
13 14 15 16 17 18 19 20 21 22 23 24 |
# File 'lib/light_mapper.rb', line 13 def self.key_destructor(value) case value in String value.split('.') in Symbol [value] in Array value else raise InvalidKey, "Invalid key type: #{value.class}" end end |
.raise_key_missing(current, full_path, additional_message = nil) ⇒ Object
8 9 10 11 |
# File 'lib/light_mapper.rb', line 8 def self.raise_key_missing(current, full_path, = nil) raise KeyMissing, ["#{current} key not found; Full path #{full_path.map(&:to_s).join('.')}", ].compact.join('; ') end |
.value_extractor(object, current, path, full_path, strict = false, any_keys = false) ⇒ Object
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
# File 'lib/light_mapper.rb', line 26 def self.value_extractor(object, current, path, full_path, strict = false, any_keys = false) result = case object in Hash hash_key_extractor(object, current, full_path, strict, any_keys) in Array array_key_extractor(object, current, full_path, strict, any_keys) in NilClass nil else method_name = current.to_s.to_sym object.respond_to?(method_name) ? object.send(method_name) : !strict ? nil : raise_key_missing(current, full_path) end path.compact.empty? ? result : value_extractor(result, path.first, path[1..-1], full_path, strict, any_keys) end |