Created
November 9, 2012 09:45
-
-
Save cantin/4044866 to your computer and use it in GitHub Desktop.
ruby-stb-lib forwardable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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