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



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.



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.



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

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.send(@setter_method_name, new_value)
    [:dirty, result, data]
  in :pop
    data.send(@setter_method_name, nil)
    [:dirty, value, data]
  end
end