Class: At::InstanceVariableDelegator

Inherits:
Object
  • Object
show all
Defined in:
lib/at/instance_variable_delegator.rb

Overview

InstanceVariableDelegator is a simply class which delegates it’s methods it an object’s instance variables.

Instance Method Summary collapse

Constructor Details

#initialize(parent) ⇒ InstanceVariableDelegator

Returns a new instance of InstanceVariableDelegator.

Parameters:

  • parent (Object)

    The object to delegate accessors to it’s instance variables.



7
8
9
# File 'lib/at/instance_variable_delegator.rb', line 7

def initialize(parent)
  @parent = parent
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(meth, value = nil) ⇒ Object

If the method ends with an equal sign (‘=`), we will set the instance variable on the @parent object. Otherwise, we will /get/ the instance variable on the @parent object.



13
14
15
16
17
18
19
20
21
# File 'lib/at/instance_variable_delegator.rb', line 13

def method_missing(meth, value=nil)
  @parent.instance_eval do
    match = meth.to_s.match(/(.*)\=$/)
    raise ArgumentError, '`value` must be given' if match && value.nil?
    raise ArgumentError, '`value` must not be given' if !match && !value.nil?
    
    match ? instance_variable_set("@#{match[1]}", value) : instance_variable_get("@#{meth}")
  end
end