Module: CowProxy::Indexable

Included in:
Array, Hash
Defined in:
lib/cow_proxy/indexable.rb

Overview

A mixin to add wrapper getter and copy-on-write for indexable classes, such as Array and Hash, i.e. classes with [] method

Instance Method Summary collapse

Instance Method Details

#[](index) ⇒ Object

Calls [](index) in wrapped object and keep wrapped value, so same wrapped value is return on following calls with same index.

Returns:

  • CowProxy wrapped value from wrapped object



11
12
13
14
15
16
17
18
19
20
21
# File 'lib/cow_proxy/indexable.rb', line 11

def [](index)
  return @hash[index] if @hash&.has_key?(index)

  begin
    value = __getobj__[index]
    return value if @hash.nil?
    wrap_value = __wrap__(value)
    @hash[index] = wrap_value if wrap_value
    wrap_value || value
  end
end

#dig(key, *args) ⇒ Object

Extracts the nested value specified by the sequence of idx objects by calling dig at each step, returning nil if any intermediate step is nil.

Returns:

  • CowProxy wrapped value from wrapped object



27
28
29
30
# File 'lib/cow_proxy/indexable.rb', line 27

def dig(key, *args)
  value = self[key]
  args.empty? ? value : value&.dig(*args)
end

#initializeObject

Extends Base#initialize



33
34
35
36
# File 'lib/cow_proxy/indexable.rb', line 33

def initialize(*)
  super
  @hash = {}
end