class Accessory::Accessors::InstanceVariableAccessor

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

Public Class Methods

new(ivar_name, default: nil) click to toggle source

@param ivar_name [Symbol] the instance-variable name @param default [Object] the default to use if the predecessor accessor passes nil data

Calls superclass method Accessory::Accessor::new
# 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

Public Instance Methods

ensure_valid(traversal_result) click to toggle source

@!visibility private

# File lib/accessory/accessors/instance_variable_accessor.rb, line 36
def ensure_valid(traversal_result)
  traversal_result || Object.new
end
get(data) { |value| ... } click to toggle source

Finds data.instance_variable_get(:"@#{ivar_name}"), feeds it down the accessor chain, and returns the result. @param data [Object] the object to traverse @return [Object] the value derived from the rest of the accessor chain

# 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) { |value| ... } click to toggle source

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

@param data [Object] the object to traverse @return [Array] a two-element array containing 1. the original value found; and 2. the result value from the accessor chain

# 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
inspect_args() click to toggle source

@!visibility private

# File lib/accessory/accessors/instance_variable_accessor.rb, line 31
def inspect_args
  @ivar_name.to_s
end
traverse(data) click to toggle source

@!visibility private

# File lib/accessory/accessors/instance_variable_accessor.rb, line 41
def traverse(data)
  data.instance_variable_get(@ivar_name)
end