Class: Accessory::Accessors::AttributeAccessor

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

Overview

Traverses an abstract “attribute” of an arbitrary object, represented by a named getter/setter method pair.

For example, AttributeAccessor.new(:foo) will traverse through the getter/setter pair .foo and .foo=.

The abstract “attribute” does not have to correspond to an actual attr_accessor; the AttributeAccessor will work as long as the relevant named getter/setter methods exist on the receiver.

Aliases

Default constructor used by predecessor accessor

  • OpenStruct.new

Instance Method Summary collapse

Methods inherited from Accessory::Accessor

#traverse_or_default

Constructor Details

#initialize(attr_name, default: nil) ⇒ AttributeAccessor

Returns a new instance of AttributeAccessor.

Parameters:

  • attr_name (Symbol)

    the attribute name (i.e. name of the getter method)

  • default (Object) (defaults to: nil)

    the default to use if the predecessor accessor passes nil data



25
26
27
28
29
# File 'lib/accessory/accessors/attribute_accessor.rb', line 25

def initialize(attr_name, default: nil)
  super(default)
  @getter_method_name = :"#{attr_name}"
  @setter_method_name = :"#{attr_name}="
end

Instance Method Details

#get(data) ⇒ Object

Finds data.send(:"#{attr_name}"), feeds it down the accessor chain, and returns the result.

Parameters:

  • data (Object)

    the object to traverse

Returns:

  • (Object)

    the value derived from the rest of the accessor chain



68
69
70
71
72
73
74
75
76
# File 'lib/accessory/accessors/attribute_accessor.rb', line 68

def get(data)
  value = traverse_or_default(data)

  if block_given?
    yield(value)
  else
    value
  end
end

#get_and_update(data) ⇒ Array

Finds data.send(:"#{attr_name}"), feeds it down the accessor chain, and uses data.send(:"#{attr_name}=") to overwrite the stored value with the returned result.

If :pop is returned from the accessor chain, the stored value will be overwritten with ‘nil`.

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



87
88
89
90
91
92
93
94
95
96
97
98
# File 'lib/accessory/accessors/attribute_accessor.rb', line 87

def get_and_update(data)
  value = traverse_or_default(data)

  case yield(value)
  in [result, new_value]
    data.send(@setter_method_name, new_value)
    [result, data]
  in :pop
    data.send(@setter_method_name, nil)
    [value, data]
  end
end