Created
November 5, 2014 12:27
-
-
Save crguezl/6376214ef8daee6cee7b to your computer and use it in GitHub Desktop.
Delegation using rails delegate method
This file contains hidden or 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 "rails" | |
module I | |
def f | |
puts "#{self.class}: doing f()" | |
end | |
def g | |
puts "#{self.class}: doing g()" | |
end | |
end | |
class A | |
include I | |
end | |
class B | |
include I | |
end | |
class C | |
attr_accessor :i | |
delegate :f, :g, :to => :i | |
def initialize(klass = A) | |
self.i = klass.new | |
end | |
end | |
c = C.new | |
c.f # output: A: doing f() | |
c.g # output: A: doing g() | |
c = C.new(B) | |
c.f # output: B: doing f() | |
c.g # output: B: doing g() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment