module CowProxy::Indexable

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

Public Class Methods

new(*) click to toggle source

Extends {CowProxy::Base#initialize}

Calls superclass method
# File lib/cow_proxy/indexable.rb, line 33
def initialize(*)
  super
  @hash = {}
end

Public Instance Methods

[](index) click to toggle source

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

@return CowProxy wrapped value from wrapped object

# 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) click to toggle source

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.

@return CowProxy wrapped value from wrapped object

# File lib/cow_proxy/indexable.rb, line 27
def dig(key, *args)
  value = self[key]
  args.empty? ? value : value&.dig(*args)
end

Protected Instance Methods

__copy_on_write__(*) click to toggle source

Copy wrapped values to duplicated wrapped object @see CowProxy::Base#copy_on_write @return duplicated wrapped object

Calls superclass method
# File lib/cow_proxy/indexable.rb, line 43
def __copy_on_write__(*)
  super.tap do
    if @hash
      @hash.each do |k, v|
        __getobj__[k] = v
      end
      @hash.clear
    end
  end
end