From: "David A. Black" Date: 2008-09-02T03:24:15+09:00 Subject: Re: included() vs extended() Hi -- On Tue, 2 Sep 2008, Maciej Tomaka wrote: > >> So my question is: given that extend() is implemented (I think) using >> metclass.include(), and that the end result of both is identical, how >> come >> Hooks.included is not called when using extend()? It seems reasonable >> that >> both the included() and extended() hooks should be called in this >> situation, >> though I can just as well see the argument against doing this. Anyone >> care >> to enlighten/persuade me as to why this behaviour exists? > > In ruby everything is an object. So even class is an object. > Still we have extend and include which are not the same methods: > > include => includes code into class. > > extend => extends using module, appends class methods. include and extend both do the same thing: they add a module to the method lookup path of an object or set of objects. So, for example: class C end c = C.new c.talk # looks in C, Object, Kernel # no 'talk' method found: error module M def talk puts "hi" end end class C include M end c.talk # looks in C, M ...stops there because it finds 'talk' No code is added to C. When you use extend, you're doing an "include" operation on the object's singleton class. So: str = "hello" str.extend(M) str.talk # looks in its singleton class, then M... # and finds 'talk' If you do, for example: C.extend(M) then you're adding M to the lookup path of C. That means you can do: C.talk But note that it's exactly the same pattern as before. > bar = Bar.new > > bar - object of class Bar > bar.class - class of object bar > Bar - class Bar, object of class Class > Bar.metaclass - class of class Bar :) The class of class Bar is Class. The singleton class of Bar isn't the same as the class of Bar. David -- Rails training from David A. Black and Ruby Power and Light: Intro to Ruby on Rails January 12-15 Fort Lauderdale, FL Advancing with Rails January 19-22 Fort Lauderdale, FL * * Co-taught with Patrick Ewing! See http://www.rubypal.com for details and updates!