From: Michael Garriss Date: 2003-08-12T08:04:32+09:00 Subject: Re: newbie mixin questions dblack@superlink.net wrote: >Hi -- > >On Tue, 12 Aug 2003, Michael Garriss wrote: > > > >>Gennady wrote: >> >> >> >>>----- Original Message ----- >>>From: "Michael Garriss" >>>To: "ruby-talk ML" >>>Sent: Monday, August 11, 2003 3:16 PM >>>Subject: newbie mixin questions >>> >>> >>> >>> >>> >>> >>>>Hi, >>>> Just 2 questions: >>>> >>>>1) How can I mixin a class method (not an instance method)? >>>> >>>> >>>> >>>> >>>class A >>> class << self >>> include SomeModule >>>end >>>end >>> >>> >>> >>> >>Very cool. Will this require me to have two seperate modules though? >>One for including class methods and the other of including the instance >>methods. >> >> > >No, modules are very modular and can fit almost anywhere :-) > >Here's a little illustration of how and why this works. > >Step 1: create a module > > module SomeModule > def talk > puts "hi" > end > end > >and include it in a class in the usual way: > > class A > include SomeModule > end > >Now all instances of A can talk: > > A.new.talk # hi > >Now, by way of parallel example: instead of class A, do the same thing >with class Class: > > class Class > include SomeModule > end > >Now all instances of Class can talk: > > A.talk # hi > String.talk # hi > Class.new.talk # hi > >That, by the way, is the heart of class methods: essentially, adding >instance methods to objects which are instances of Class. > >The only problem is that you probably don't want all Class objects to >talk; you only want A to talk. So actually, instead of the above, you >can do what Gennady did, which restricts the addition of 'talk' to >just the one Class object (A): > > class A > class << self # operating just on A's singleton class, > include SomeModule # so only A will gain the ability to talk > end > end > > A.talk # hi > String.talk # error! only added 'talk' capability to A > > >David > > > Thank you for the explanation. I'm still a bit confused about something though: module Example def method_I_want_to_be_a_class_method # whatever end def mehtod_I_want_to_be_an_instance_method # whatever end end class A include Example class << self include Example end end How do I seperate the class methods from the instance methods in the module? In my above code I'll have one extra unwanted class and one extra unwanted instance method. Michael