Module: CowProxy::Indexable
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
-
#[](index) ⇒ Object
Calls [](index) in wrapped object and keep wrapped value, so same wrapped value is return on following calls with same index.
-
#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.
-
#initialize ⇒ Object
Extends Base#initialize.
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.
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.
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 |
#initialize ⇒ Object
Extends Base#initialize
33 34 35 36 |
# File 'lib/cow_proxy/indexable.rb', line 33 def initialize(*) super @hash = {} end |