Class: KeyMapable::Mapper

Inherits:
Object
  • Object
show all
Defined in:
lib/key_mapable/mapper.rb

Overview

Used internally by the KeyMapable concern.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(subject, accessor = KeyMapable::Accessor::Method) ⇒ Mapper

Returns a new instance of Mapper.



7
8
9
10
11
# File 'lib/key_mapable/mapper.rb', line 7

def initialize(subject, accessor = KeyMapable::Accessor::Method)
  @subject = subject
  @structure = {}
  @accessor = accessor
end

Instance Attribute Details

#accessorObject (readonly)

Returns the value of attribute accessor.



5
6
7
# File 'lib/key_mapable/mapper.rb', line 5

def accessor
  @accessor
end

#structureObject (readonly)

Returns the value of attribute structure.



5
6
7
# File 'lib/key_mapable/mapper.rb', line 5

def structure
  @structure
end

#subjectObject (readonly)

Returns the value of attribute subject.



5
6
7
# File 'lib/key_mapable/mapper.rb', line 5

def subject
  @subject
end

Instance Method Details

#array_key_map(original_key, new_key, &block) ⇒ Object



35
36
37
38
39
40
41
42
# File 'lib/key_mapable/mapper.rb', line 35

def array_key_map(original_key, new_key, &block)
  original_subject = access(original_key)
  @structure[new_key] = original_subject.map do |item|
    child_mapper = self.class.new(item, accessor)
    child_mapper.instance_eval(&block)
    child_mapper.resolve
  end
end

#key(name, &block) ⇒ Object



17
18
19
20
21
# File 'lib/key_mapable/mapper.rb', line 17

def key(name, &block)
  child_mapper = self.class.new(subject, accessor)
  child_mapper.instance_eval(&block)
  @structure[name] = child_mapper.resolve
end

#key_map(original_key, new_key, transform: ->(val) { val }, &block) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
# File 'lib/key_mapable/mapper.rb', line 23

def key_map(original_key, new_key, transform: ->(val) { val }, &block)
  original_subject = access(original_key)
  transformed_subject = transform.call(original_subject)
  if block_given?
    child_mapper = self.class.new(transformed_subject, accessor)
    child_mapper.instance_eval &block
    @structure[new_key] = child_mapper.resolve
  else
    @structure[new_key] = transformed_subject
  end
end

#key_value(key) ⇒ Object



13
14
15
# File 'lib/key_mapable/mapper.rb', line 13

def key_value(key)
  @structure[key] = yield(subject)
end

#resolveObject



44
45
46
# File 'lib/key_mapable/mapper.rb', line 44

def resolve
  @structure
end