Class: Each

Inherits:
Object
  • Object
show all
Defined in:
lib/ruby-optics/each.rb

Defined Under Namespace

Classes: Filter

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(outer_focus = nil, inner_focus = nil, filter = nil) ⇒ Each

Returns a new instance of Each.



14
15
16
17
18
# File 'lib/ruby-optics/each.rb', line 14

def initialize(outer_focus = nil, inner_focus = nil, filter = nil)
  @outer_focus = outer_focus || Lens.identity
  @inner_focus = inner_focus || Lens.identity
  @filter = filter
end

Instance Attribute Details

#filterObject (readonly)

Returns the value of attribute filter.



6
7
8
# File 'lib/ruby-optics/each.rb', line 6

def filter
  @filter
end

#inner_focusObject (readonly)

Returns the value of attribute inner_focus.



4
5
6
# File 'lib/ruby-optics/each.rb', line 4

def inner_focus
  @inner_focus
end

#outer_focusObject (readonly)

Returns the value of attribute outer_focus.



5
6
7
# File 'lib/ruby-optics/each.rb', line 5

def outer_focus
  @outer_focus
end

Class Method Details

.with_filter(focusing_lens, &blk) ⇒ Object



56
57
58
# File 'lib/ruby-optics/each.rb', line 56

def self.with_filter(focusing_lens, &blk)
  Each.new.with_filter(focusing_lens, &blk)
end

Instance Method Details

#compose_lens(lens) ⇒ Object



48
49
50
51
52
53
54
# File 'lib/ruby-optics/each.rb', line 48

def compose_lens(lens)
  Each.new(
    outer_focus = self.outer_focus,
    inner_focus = self.inner_focus.compose_lens(lens),
    filter      = self.filter
  )
end

#get_all(object) ⇒ Object



36
37
38
# File 'lib/ruby-optics/each.rb', line 36

def get_all(object)
  filtered(outer_focus.get(object)).map { |a| inner_focus.get(a) }
end

#modify_all(object, &blk) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
# File 'lib/ruby-optics/each.rb', line 24

def modify_all(object, &blk)
  outer_focus.modify(object) { |enumerable|
    enumerable.map { |a|
      if !filter.nil?
        filter.call(a) ? inner_focus.modify(a, &blk) : a
      else
        inner_focus.modify(a, &blk)
      end
    }
  }
end

#set(new_value, object) ⇒ Object



20
21
22
# File 'lib/ruby-optics/each.rb', line 20

def set(new_value, object)
  modify_all(object) { |_| new_value }
end

#with_filter(focusing_lens, &blk) ⇒ Object



40
41
42
43
44
45
46
# File 'lib/ruby-optics/each.rb', line 40

def with_filter(focusing_lens, &blk)
  Each.new(
    outer_focus = self.outer_focus,
    inner_focus = self.inner_focus,
    filter      = Filter.new(focusing_lens, blk)
  )
end