Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
# 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
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
@iain

This comment has been minimized.

Copy link

@iain iain commented Sep 19, 2010

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment