混入

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"