From: Ara.T.Howard@... Date: 2005-04-30T04:44:29+09:00 Subject: Re: determining when inside 'class << self' On Fri, 29 Apr 2005, Robert Klemme wrote: > class Object > def inside_metaclass?() false end > end > > class Class > def inside_metaclass? > begin > self.allocate > false > rescue TypeError => e > /virtual class/i =~ e.to_s and true > end > end > end > > irb(main):058:0> class < true > => nil > irb(main):059:0> p inside_metaclass? > false > => nil > irb(main):060:0> class String; p inside_metaclass? end > false > => nil > > Cheers > > robert hmm. i like this more than the pure matching version - which seemed a bit fragile. seems like i could do harp:~ > cat a.rb class Object def inside_metaclass? begin allocate() false rescue NoMethodError false rescue TypeError => e %r/virtual class/i =~ e.to_s and true end end end obj = Object::new klass = Class::new p inside_metaclass? #=> false class << obj p inside_metaclass? #=> true end class << klass p inside_metaclass? #=> true end class << self p inside_metaclass? #=> true end harp:~ > ruby a.rb false true true true too. now - any opinions on whether this violates POLS or not: # # my attributes module - hoping to become a collection of better 'attr' like # metamethods... # require 'attributes' class C # # define a class attr => used like C::foo # class_attribute 'foo' # # define an instance attr => C::new.bar # attribute 'bar' class << self # # define a class attr => used like C::foobar # # note that this would be the SAME as using class_attribute 'foobar' # outside of metaclass # attribute 'foobar' end end so, you see, Object::attribute would be context sensitive to being inside a metaclass or not - if inside a Class.metaclass it's defining a class attribute, else an instance attribute. thoughts? -a -- =============================================================================== | email :: ara [dot] t [dot] howard [at] noaa [dot] gov | phone :: 303.497.6469 | renunciation is not getting rid of the things of this world, but accepting | that they pass away. --aitken roshi ===============================================================================