Skip to content

Instantly share code, notes, and snippets.

@fronx
Forked from svenfuchs/include_anonymous.rb
Created September 18, 2010 13:19
Show Gist options
  • Save fronx/585663 to your computer and use it in GitHub Desktop.
Save fronx/585663 to your computer and use it in GitHub Desktop.
# 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment