Ruby Forwardable Module For Delegation

Ruby's Forwardable module provides delegation of specified methods to a designated object.

This page has an example.

Define a typical class:

  class Foo

    def hello
      puts "world"
    end

  end

Define a class that will forward to Foo:

  require 'forwardable'

  class Bar
    extend Forwardable
    def_delegators :foo, :hello

    def foo
      @foo||=Foo.new
    end

  end

Now create an object and watch it forward to another object:

  bar=Bar.new
  bar.hello => "world"



What's Next?

blog comments powered by Disqus