Skip to content

Instantly share code, notes, and snippets.

@crguezl
Created November 5, 2014 12:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crguezl/6376214ef8daee6cee7b to your computer and use it in GitHub Desktop.
Save crguezl/6376214ef8daee6cee7b to your computer and use it in GitHub Desktop.
Delegation using rails delegate method
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