mugyu
6/1/2014 - 4:36 AM

クラスメソッドとインスタンスメソッドをミックスイン

クラスメソッドとインスタンスメソッドをミックスイン

# will mix-in instance and class methods.
module SameModule
  def self.included(base)
    base.extend ClassMethods
  end

  module ClassMethods
    def foo(msg)
      puts msg
    end
  end

  # instance methods
  def foo(msg)
    self.class.foo(msg)
  end
end

class SameClass
  include SameModule

  foo "test1"

  def bar
    puts "bar"
    foo "test2"
  end
end

puts "----"
SameClass.foo "test3"
puts "----"
obj = SameClass.new
obj.foo "test4"
puts "----"
obj.bar

# => test1
# => ----
# => test3
# => ----
# => test4
# => ----
# => bar
# => test2