Skip to content

Instantly share code, notes, and snippets.

@tjsingleton
Created July 8, 2010 08:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tjsingleton/467769 to your computer and use it in GitHub Desktop.
Save tjsingleton/467769 to your computer and use it in GitHub Desktop.
# 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
# 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
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