Class: Monolens::Object::Select

Inherits:
Object
  • Object
show all
Includes:
Lens
Defined in:
lib/monolens/object/select.rb

Instance Attribute Summary

Attributes included from Lens

#options

Instance Method Summary collapse

Methods included from Lens

#fetch_on, #is_array!, #is_enumerable!, #is_hash!, #is_string!, #option

Constructor Details

#initialize(selection) ⇒ Select

Returns a new instance of Select.



6
7
8
9
# File 'lib/monolens/object/select.rb', line 6

def initialize(selection)
  super({})
  @selection = selection
end

Instance Method Details

#call(arg, *rest) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/monolens/object/select.rb', line 11

def call(arg, *rest)
  is_hash!(arg)

  result = {}
  @selection.each_pair do |new_attr, selector|
    is_array = selector.is_a?(::Array)
    is_symbol = false
    values = Array(selector).map do |old_attr|
      actual, fetched = fetch_on(old_attr, arg)
      is_symbol ||= actual.is_a?(Symbol)
      fetched
    end
    new_attr = is_symbol ? new_attr.to_sym : new_attr.to_s
    result[new_attr] = is_array ? values : values.first
  end
  result
end