Created
September 18, 2010 12:46
-
-
Save svenfuchs/585630 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
# Include an anonymous module | |
# | |
# Useful for defining a class with a base module. So, instead of: | |
# | |
# class Foo | |
# module Base | |
# def bar | |
# # ... | |
# end | |
# end | |
# include Base | |
# end | |
# | |
# You can do: | |
# | |
# class Foo | |
# include do | |
# def bar | |
# # ... | |
# end | |
# end | |
# end | |
Class.class_eval do | |
def include(*args, &block) | |
block_given? ? super(Module.new(&block)) : super(*args) | |
end | |
end |
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
class IncludeAnonymousTest < Test::Unit::TestCase | |
def teardown | |
self.class.send(:remove_const, :A) | |
end | |
test 'anonymous include on a class' do | |
class A | |
include { def foo; 'foo' end } | |
end | |
assert_equal 'foo', A.new.foo | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Clever code!
Reminds me of Yehuda's overridable method. If you create a method inside the anonymous module, you can override it in the class itself and call super to get to the one in the anonymous module.