From: zdennis Date: 2006-04-11T02:46:24+09:00 Subject: Re: Adding both class and instance/object methods from a Module? -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Sam Roberts wrote: > On Mon, Apr 10, 2006 at 08:57:04PM +0900, Robert Klemme wrote: > >>There's an easier way: >> >>class D >> extend M >>end >> >>or >> >>class D;end >>D.extend M > > > Is there an easy way to extend classes with both class and object > methods at the same time? > > module M > def self.create > # would do something special here > new > end > def objmethod > end > end > > class A > extend M > end > > a.create # <-- nope, doesn't work This is because you created the 'create' method as a class-like method on the mdoule, a module method. You need to create it as an instance level method. It seems to do this cleanly you'd want to separate this into two modules, one for instance level methods and one intended for class-level use: irb(main):017:0> module ClassLevelAddons irb(main):018:1> def create irb(main):019:2> new irb(main):020:2> end irb(main):021:1> end => nil irb(main):022:0> module InstanceLevelAddons irb(main):023:1> def foo irb(main):024:2> "bar" irb(main):025:2> end irb(main):026:1> end => nil irb(main):027:0> class A irb(main):028:1> extend ClassLevelAddons irb(main):029:1> include InstanceLevelAddons irb(main):030:1> end => A irb(main):031:0> A.create => # irb(main):032:0> A.new.foo => "bar" For organizational concerns you could always let one module be in charge: irb(main):001:0> module M irb(main):002:1> module ClassLevelAddons irb(main):003:2> def create; new ; end irb(main):004:2> end irb(main):005:1> irb(main):006:1* def foo irb(main):007:2> "bar" irb(main):008:2> end irb(main):009:1> irb(main):010:1* def self.included( clazz ) irb(main):011:2> clazz.extend( ClassLevelAddons ) irb(main):012:2> end irb(main):013:1> end => nil irb(main):014:0> class A ; include M; end => A irb(main):015:0> A.create => # irb(main):016:0> A.new.foo => "bar" irb(main):017:0> The above lets M take care of the work, so your class doesn't have to think about it. This is the method that Robert Klemme was refering to, Module::included Zach -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.1 (GNU/Linux) Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org iD8DBQFEOpr7Myx0fW1d8G0RApEpAJsEkuPmjl2cmdZJ+DWVZZXixf0iZQCffoU/ Au6m/BGG/iDIJde+dIXHzsw= =AZUA -----END PGP SIGNATURE-----