Class: Accessory::Accessors::FirstAccessor

Inherits:
Accessory::Accessor show all
Defined in:
lib/accessory/accessors/first_accessor.rb

Overview

Traverses into the “first” element within an Enumerable, using #first.

This accessor can be preferable to SubscriptAccessor for objects that are not subscriptable, e.g. Range.

Aliases

Default constructor used by predecessor accessor

  • Array.new

Instance Method Summary collapse

Methods inherited from Accessory::Accessor

#traverse_or_default

Instance Method Details

#get(data) ⇒ Object

Feeds data.first down the accessor chain, returning the result.

Parameters:

  • data (Object)

    the object to traverse

Returns:

  • (Object)

    the value derived from the rest of the accessor chain



39
40
41
42
43
44
45
46
47
# File 'lib/accessory/accessors/first_accessor.rb', line 39

def get(data)
  value = traverse_or_default(data)

  if block_given?
    yield(value)
  else
    value
  end
end

#get_and_update(data) ⇒ Array

Finds data.first, feeds it down the accessor chain, and overwrites the stored value with the returned result.

If :pop is returned from the accessor chain, the stored value will be removed using data.delete_at(0).

Parameters:

  • data (Object)

    the object to traverse

Returns:

  • (Array)

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



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/accessory/accessors/first_accessor.rb', line 57

def get_and_update(data)
  old_value = traverse_or_default(data)

  case yield(old_value)
  in [result, new_value]
    if data.respond_to?(:"first=")
      data.first = new_value
    else
      data[0] = new_value
    end
    [result, data]
  in :pop
    data.delete_at(0)
    [old_value, data]
  end
end