From: ara.t.howard@... Date: 2006-10-19T00:14:01+09:00 Subject: Re: Mixin a module method as a class method On Wed, 18 Oct 2006, Farrel Lifson wrote: > Is it possible to mix in a module method to become a class method? I'd > like to define the method_added method in a module and then mix it > into a class like so > module Foo > def self.method_added(method) > puts "Added #{method}" > end > end > > class Bar > include Foo > def bar > end > def baz > end > end > So that I get > Added bar > Added baz > printed out. Is there any way to do this besides making Foo a class > and subclassing Foo from it? > > Farrel harp:~ > cat a.rb module Foo #def self.method_added(method) def method_added(method) puts "Added #{method}" end end class Bar #include Foo extend Foo def bar end def baz end end harp:~ > ruby a.rb Added bar Added baz if you need both instance and class methods to be in Foo, then you'll want: harp:~ > cat a.rb module Foo #def self.method_added(method) module ClassMethods def method_added(method) puts "Added #{method}" end end module InstanceMethods def foo() 42 end end def self.included other other.module_eval{ extend ClassMethods include InstanceMethods } end end class Bar include Foo def bar end def baz end end p Bar.new.foo harp:~ > ruby a.rb Added bar Added baz 42 -a -- my religion is very simple. my religion is kindness. -- the dalai lama