From: "Mauricio Fernández" Date: 2003-01-22T20:06:36+09:00 Subject: Re: accessors for module instance vars On Wed, Jan 22, 2003 at 06:00:03PM +0900, Phil Tomson wrote: > In article , > ahoward wrote: > >On 22 Jan 2003, Phil Tomson wrote: > >> And if I leave it as a module it could be mixed into a class later (though > >> that's not how I'm using it now) and all of the 'module instance variables' > >> would also end up in the class it was mixed into.... > > > >i don't think it works that way : > > > > module M > > attr_accessor :x > > @x = 42 > > end > > > > class Foo; include M; end > > > > p Foo.new.x # >> nil > > > >the instance variable STAY in M, that's what i was referring to when i said i > >was unsure of the semantics. See my other post. > this works: > > module M > def x > if not defined? @x > @x = 0 > end > @x > end > > def x=(x) > @x=x > end > end > > class Foo; include M; end > > Foo.new.x #-> 0 But you're not using the module instance variable of M! > However, those are instance methods (x and x=) defined in module M and > since M can't be instantiated they are only callable after M is mixed into > a class and an instance of that class is created. > > I wonder if there is a way to mixin module methods so that they become > instance methods of a class? > > module M > def M.x > if not defined? @x > @x=0 > end > @x > end > end This one is. > class MyM > include_module_methods_of M #somehow > end > > MyM.new.x #-> 0 If that worked, it'd mean that you're extending one object with the singleton class of M, which is AFAIK impossible since it's a virtual class. You cannot 'transfer' singleton methods. >> module M >> def M.x >> @x >> end >> def M.x= a >> @x = a >> end >> end => nil >> M.x => nil >> M.x = 1 => 1 >> M.x => 1 >> singleton_class = class << M; self; end => Module >> class Foo < singleton_class >> end TypeError: can't make subclass of virtual class from (irb):13 >> singleton_class.instance_methods => ["x", "x="] >> Foo.extend singleton_class TypeError: wrong argument type Class (expected Module) from (irb):24:in `extend' from (irb):24 >> M.singleton_methods => ["x", "x="] >> Foo.extend M => Foo >> Foo.x NameError: undefined method `x' for Foo:Class from (irb):35 >> class Foo >> include M >> end => Foo >> Foo.x NameError: undefined method `x' for Foo:Class from (irb):40 >> Foo.new.x NameError: undefined method `x' for # from (irb):41 > Anyone know of a way to do this? (I have no pressing need for this, just > curious) Just wait for Guy Decoux' post to correct me and find a way or confirm it cannot be done ;-) -- _ _ | |__ __ _| |_ ___ _ __ ___ __ _ _ __ | '_ \ / _` | __/ __| '_ ` _ \ / _` | '_ \ | |_) | (_| | |_\__ \ | | | | | (_| | | | | |_.__/ \__,_|\__|___/_| |_| |_|\__,_|_| |_| Running Debian GNU/Linux Sid (unstable) batsman dot geo at yahoo dot com Do you mean to say that I can read mail with vi too? ;-) Didn't you know that? :r /var/spool/mail/jk -- debian-mentors