Class: Accessory::Accessors::AttributeAccessor
- Inherits:
-
Accessory::Accessor
- Object
- Accessory::Accessor
- Accessory::Accessors::AttributeAccessor
- 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
-
Accessory::Access::FluentHelpers#attr (included in Lens and BoundLens)
Default constructor used by predecessor accessor
-
OpenStruct.new
Instance Method Summary collapse
-
#get(data) ⇒ Object
Finds
data.send(:"#{attr_name}")
, feeds it down the accessor chain, and returns the result. -
#get_and_update(data) ⇒ Array
Finds
data.send(:"#{attr_name}")
, feeds it down the accessor chain, and usesdata.send(:"#{attr_name}=")
to overwrite the stored value with the returned result. -
#initialize(attr_name, default: nil) ⇒ AttributeAccessor
constructor
A new instance of AttributeAccessor.
Methods inherited from Accessory::Accessor
Constructor Details
#initialize(attr_name, default: nil) ⇒ AttributeAccessor
Returns a new instance of 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 |
# 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 |