Class: Accessory::Accessors::SubscriptAccessor

Inherits:
Accessory::Accessor show all
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

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

Methods inherited from Accessory::Accessor

#traverse_or_default

Instance Method Details

#get(data) ⇒ Object

Finds data[@key], feeds it down the accessor chain, and returns the result.

Parameters:

  • data (Enumerable)

    the Enumerable to index into

Returns:

  • (Object)

    the value derived from the rest of the accessor chain



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).

Parameters:

  • data (Enumerable)

    the Enumerable to index into

Returns:

  • (Array)

    a two-element array containing 1. the original value found; and 2. the result value from the accessor chain



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