module SomeMixin
def foo
puts "foo!"
end
end
class Bar
include SomeMixin
def baz
puts "baz!"
end
end
b = Bar.new
b.baz # => "baz!"
b.foo # => "foo!"
# works thanks to the mixin
Now Bar is a mix of it...
Modules can contain other modules and classes:
module Namespace
module Child
class Foo; end
end # module Child
# Foo can now be accessed as:
#
Child::Foo
end # module Namespace
# Foo must now be accessed as:
#
Namespace::Child::Foo
A mixin is just a module that can be added (mixed in) to a class. one way to do it is with the extend method. The extend method adds methods of the mixin as class methods.
module SomeMixin
def foo
puts "foo!"
end
end
class Bar
extend SomeMixin
def baz
puts "...
You can use Modules to build more complex classes through composition. The include ModuleName directive incorporates a module's methods into a class.
module Foo
def foo_method
puts 'foo_method called!'
end
end
module Bar
def bar_method
puts 'bar_method called!'
end
end
...