From: Rick DeNatale Date: 2006-10-19T09:42:16+09:00 Subject: Re: Mixin a module method as a class method On 10/18/06, ara.t.howard@noaa.gov wrote: > 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 No need for the separate module for instance methods; rick@frodo:/public/rubyscripts$ cat a1.rb module Foo module ClassMethods def method_added(method) puts "Added #{method}" end end def self.included(other) other.extend ClassMethods end def foo 42 end end class Bar include Foo def bar end def baz end end p Bar.new.foo rick@frodo:/public/rubyscripts$ ruby a1.rb Added bar Added baz 42 -- Rick DeNatale My blog on Ruby http://talklikeaduck.denhaven2.com/