← til

Forwardable explained

May 12, 2012

There's a pretty cool module called Forwardable and it's used for delegation. Let me explain this a little better...

Delegation is a design pattern in which an object delegates its own method to another object.

Why would you ever need that?

Here's an example:

require 'forwardable'

class Employers
  extend Forwardable

  attr_reader :all

  def_delegator :@all,:length,:size

  def initialize(*ids)
    @all = ids

employers = Employers.new(1,2,3,4)
puts employers.size # => 4

We have declared a new method on our instance variable, so we when we call size on it, it will forward our call to length.