Module: Grizzled::Forwarder

Included in:
Grizzled::FileUtil::Includer
Defined in:
lib/grizzled/forwarder.rb

Overview

Forwarder makes it easy to forward calls to another object.

Examples:

Forward all unimplemented methods to a file:

class Test
  include Grizzled::Forwarder

  def initialize(file)
    forward_to file
  end
end

Test.new(File.open('/tmp/foobar')).each_line do |line|
  puts(line)
end

Forward all unimplemented calls, except each to the specified object. Calls to each will raise a NoMethodError:

class Test
  include Grizzled::Forwarder

  def initialize(file)
    forward_to file, [:each]
  end
end

Instance Method Summary collapse

Instance Method Details

#forward_to(obj, exceptions = []) ⇒ Object

Forward all unimplemented method calls to obj, except those whose symbols are listed in the exceptions array.

Parameters:

obj

The object to which to forward unimplemented method calls

exception+

A list of symbols for unimplemented methods that should not be forwarded to obj. Note: You do not have to put methods you’ve implemented in here.



80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
# File 'lib/grizzled/forwarder.rb', line 80

def forward_to(obj, exceptions=[])
  @forward_obj = obj

  require 'set'

  @forwarder_exceptions = Set.new(exceptions)
  class << self
    def method_missing(m, *args, &block)
      if not @forwarder_exceptions.include? m
        @forward_obj.send(m, *args, &block)
      else
        super(m, *args, &block)
      end
    end
  end
end