混入

Mixins 是一种实现类似于多重继承的美妙方式。它允许我们继承或者更确切地将模块中定义的方法包含到类中。这些方法可以作为实例或类方法包含在内。以下示例描述了此设计。

module SampleModule

  def self.included(base)
    base.extend ClassMethods
  end

  module ClassMethods

    def method_static
      puts "This is a static method"
    end

  end

  def insta_method
    puts "This is an instance method"
  end

end

class SampleClass
  include SampleModule
end

sc = SampleClass.new

sc.insta_method

prints "This is an instance method"

sc.class.method_static

prints "This is a static method"