Skip to content

Instantly share code, notes, and snippets.

@danhodge
Last active August 29, 2015 13:57
Show Gist options
  • Save danhodge/9784715 to your computer and use it in GitHub Desktop.
Save danhodge/9784715 to your computer and use it in GitHub Desktop.
Ruby Delegators
require 'forwardable'
class Foo
extend Forwardable
# Note: def_delegators, not def_delegator
def_delegators :ar, :size, :map
def ar
[1, 2, 3]
end
end
f = Foo.new
f.size # => 3
f.map { |x| x * 2 } # => [2, 4, 6]
# f.each # => NoMethodError
require 'forwardable'
module Foo
extend self
extend Forwardable
# Note: def_delegators, not def_delegator
def_delegators :ar, :size, :map
def ar
[1, 2, 3]
end
end
Foo.size # => 3
Foo.map { |x| x * 2 } # => [2, 4, 6]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment