Module: ForwardTo

Defined in:
lib/forward_to.rb,
lib/forward_to/version.rb

Constant Summary collapse

VERSION =
"0.3.0"

Instance Method Summary collapse

Instance Method Details

#forward_to(target, *methods) ⇒ Object

Forward methods to member object. The arguments should be strings or symbols

Forward to takes the first argument and creates methods for the rest of the arguments that forward their call to the first argument. Example

include ForwardTo

class MyArray
  forward_to :@implementation, :empty?, :size, :[]

  def initialize()
    @implementation = []
  end
end

a = MyArray.new
a.size # -> 0
a.empty? # -> true
a[0] = 1
a[0] # -> 1

The target of #forward_to can be a method or a member (@variable) but has to be a symbol



30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/forward_to.rb', line 30

def forward_to(target, *methods)
  for method in Array(methods).flatten
    case method
      when /\[\]=/
        class_eval("def #{method}(*args) #{target}&.#{method}(*args) end")
      when /=$/
        class_eval("def #{method}(args) #{target}&.#{method}(args) end")
      else
        class_eval("def #{method}(*args, &block) #{target}&.#{method}(*args, &block) end")
    end
  end
end