Class: Accessory::Accessors::InstanceVariableAccessor
- Inherits:
-
Accessory::Accessor
- Object
- Accessory::Accessor
- Accessory::Accessors::InstanceVariableAccessor
- Defined in:
- lib/accessory/accessors/instance_variable_accessor.rb
Overview
Traverses into a named instance-variable of an arbitrary object.
For example, given InstanceVariableAccessor.new(:foo)
, the instance-variable @foo
of the input data will be traversed.
Aliases
-
Accessory::Access::FluentHelpers#ivar (included in Lens and BoundLens)
Default constructor used by predecessor accessor
-
Object.new
Instance Method Summary collapse
-
#get(data) ⇒ Object
Finds
data.instance_variable_get(:"@#{ivar_name}")
, feeds it down the accessor chain, and returns the result. -
#get_and_update(data) ⇒ Array
Finds
data.instance_variable_get(:"@#{ivar_name}")
, feeds it down the accessor chain, and usesdata.instance_variable_set(:"@#{ivar_name}")
to overwrite the stored value with the returned result. -
#initialize(ivar_name, default: nil) ⇒ InstanceVariableAccessor
constructor
A new instance of InstanceVariableAccessor.
Methods inherited from Accessory::Accessor
Constructor Details
#initialize(ivar_name, default: nil) ⇒ InstanceVariableAccessor
Returns a new instance of InstanceVariableAccessor.
20 21 22 23 24 25 26 27 28 |
# File 'lib/accessory/accessors/instance_variable_accessor.rb', line 20 def initialize(ivar_name, default: nil) super(default) ivar_name = ivar_name.to_s ivar_name = "@#{ivar_name}" unless ivar_name.to_s.start_with?("@") ivar_name = ivar_name.intern @ivar_name = ivar_name end |
Instance Method Details
#get(data) ⇒ Object
Finds data.instance_variable_get(:"@#{ivar_name}")
, feeds it down the accessor chain, and returns the result.
49 50 51 52 53 54 55 56 57 |
# File 'lib/accessory/accessors/instance_variable_accessor.rb', line 49 def get(data) value = traverse_or_default(data) if block_given? yield(value) else value end end |
#get_and_update(data) ⇒ Array
Finds data.instance_variable_get(:"@#{ivar_name}")
, feeds it down the accessor chain, and uses data.instance_variable_set(:"@#{ivar_name}")
to overwrite the stored value with the returned result.
If :pop
is returned from the accessor chain, the stored value will be removed using data.remove_instance_variable(:"@#{ivar_name}")
.
69 70 71 72 73 74 75 76 77 78 79 80 81 82 |
# File 'lib/accessory/accessors/instance_variable_accessor.rb', line 69 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.instance_variable_set(@ivar_name, new_value) [:dirty, result, data] in :pop data.remove_instance_variable(@ivar_name) [:dirty, value, data] end end |