一個簡單的 mixin 擴充套件

mixin 只是一個可以新增(混入)到類的模組。一種方法是使用 extend 方法。extend 方法將 mixin 的方法新增為類方法。

module SomeMixin
  def foo
    puts "foo!"
  end
end

class Bar
  extend SomeMixin
  def baz
    puts "baz!"
  end
end

b = Bar.new
b.baz         # => "baz!"
b.foo         # NoMethodError, as the method was NOT added to the instance
Bar.foo       # => "foo!"
# works only on the class itself