Class: Accessory::Accessors::InstanceVariableAccessor

Inherits:
Accessory::Accessor show all
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

Default constructor used by predecessor accessor

  • Object.new

Instance Method Summary collapse

Methods inherited from Accessory::Accessor

#traverse_or_default

Constructor Details

#initialize(ivar_name, default: nil) ⇒ InstanceVariableAccessor

Returns a new instance of InstanceVariableAccessor.

Parameters:

  • ivar_name (Symbol)

    the instance-variable name

  • default (Object) (defaults to: nil)

    the default to use if the predecessor accessor passes nil data



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.

Parameters:

  • data (Object)

    the object to traverse

Returns:

  • (Object)

    the value derived from the rest of the accessor chain



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}").

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



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