Mixing in Class Methods.rb : Mixins « Language Basics « Ruby






Mixing in Class Methods.rb


module MyLib
  module ClassMethods
    def class_method
      puts "in MyLib::ClassMethods"
    end
  end
end

module MyLib
  def self.included(receiver)
    puts "MyLib is being included in #{receiver}!"
    receiver.extend(ClassMethods)
  end
end

class MyClass
  include MyLib
end
# MyLib is being included in MyClass!

MyClass.class_method
# This method was first defined in MyLib::ClassMethods

 








Related examples in the same category

1.Creating Mixins
2.The Making of a Man
3.Automatically Initializing Mixed-In Modules
4.Simulating Multiple Inheritance with Mixins.rb