Created
July 8, 2010 08:36
-
-
Save tjsingleton/467769 to your computer and use it in GitHub Desktop.
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
# modules work! :) If we define_method on a module and include it, it works the same. | |
class A | |
include World | |
end | |
module World | |
def hello | |
puts "World" | |
end | |
end | |
module Hello | |
def hello | |
print "Hello, " | |
super() | |
end | |
A.send :include, self | |
end | |
A.new.hello | |
Hello, World | |
=> nil |
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
# Oh no, we can't extend #foo with a module :( This is what happens when we use define_method. | |
class B | |
include Foo | |
def foo | |
puts "bar" | |
end | |
end | |
module Foo | |
def foo | |
print "foo" | |
super | |
end | |
end | |
B.new.foo | |
bar | |
=> nil |
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
def module_backed_define_method(klass, name, &block) | |
mod = Module.new | |
mod.send :define_method, name, &block | |
klass.send :include, mod | |
end | |
module World | |
def hello | |
puts "World" | |
end | |
end | |
class A | |
include World | |
module_backed_define_method(self, :hello) do | |
print "Hello, " | |
super() | |
end | |
end | |
A.new.hello | |
Hello, World | |
=> nil |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment