Skip to content

Instantly share code, notes, and snippets.

@cantin
Created November 9, 2012 09:45
Show Gist options
  • Save cantin/4044866 to your computer and use it in GitHub Desktop.
Save cantin/4044866 to your computer and use it in GitHub Desktop.
ruby-stb-lib forwardable
require 'forwardable'
class A
extend Forwardable
def initialize
@arr = Array.new
end
def_delegator :@arr, :push, :add
def_delegators :@arr, :size, :map
end
a = A.new
puts a.size # 0
puts a.add('a') # a
puts a.size # 1
puts a.map(&:to_s) # a
class B
extend SingleForwardable
def self.arr
@arr ||= Array.new
end
def_delegator :arr, :push, :add
def_delegators :arr, :size, :map
end
puts B.size # 0
puts B.add('a') # a
puts B.size # 1
puts B.map(&:to_s) # a
=begin
if you extend both
use def_instance_delegator and def_single_delegator
end
=end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment