Class: Accessory::Accessors::SubscriptAccessor
- Inherits:
-
Accessory::Accessor
- Object
- Accessory::Accessor
- Accessory::Accessors::SubscriptAccessor
- Defined in:
- lib/accessory/accessors/subscript_accessor.rb
Overview
Traverses into a specified key
for an arbitrary container-object which supports the #[]
and #[]=
methods.
Aliases
-
Accessory::Access::FluentHelpers#subscript (included in Lens and BoundLens)
-
Accessory::Access::FluentHelpers#[] (included in Lens and BoundLens)
-
just passing a
key
will also work, when not(key.kind_of?(Accessor)) (this is a special case in Lens#initialize)
Equivalents in Elixir’s Access
module
Default constructor used by predecessor accessor
-
Hash.new
Usage Notes:
Subscripting into an Array
will work, but may not have the results you expect:
# extends the Array
[].lens[3].put_in(1) # => [nil, nil, nil, 1]
# default-constructs a Hash, not an Array
[].lens[0][0].put_in(1) # => [{0=>1}]
Other accessors (FirstAccessor, BetwixtAccessor, etc.) may fit your expectations more closely for Array
traversal.
Instance Method Summary collapse
-
#get(data) ⇒ Object
Finds
data[@key]
, feeds it down the accessor chain, and returns the result. -
#get_and_update(data) ⇒ Array
Finds
data[@key]
, feeds it down the accessor chain, and overwritesdata[@key]
with the returned result.
Methods inherited from Accessory::Accessor
Instance Method Details
#get(data) ⇒ Object
Finds data[@key]
, feeds it down the accessor chain, and returns the result.
74 75 76 77 78 79 80 81 82 |
# File 'lib/accessory/accessors/subscript_accessor.rb', line 74 def get(data) value = traverse_or_default(data) if block_given? yield(value) else value end end |
#get_and_update(data) ⇒ Array
Finds data[@key]
, feeds it down the accessor chain, and overwrites data[@key]
with the returned result.
If :pop
is returned from the accessor chain, the key is instead deleted from the data with data.delete(@key)
.
91 92 93 94 95 96 97 98 99 100 101 102 103 104 |
# File 'lib/accessory/accessors/subscript_accessor.rb', line 91 def get_and_update(data) value = traverse_or_default(data) case yield(value) in [:clean, result, _] [:clean, result, data] in [:dirty, result, new_value] data[@key] = new_value [:dirty, result, data] in :pop data.delete(@key) [:dirty, value, data] end end |