Class.new and extending it...

T

Thomas E Enebo

I am trying to do something like the following code sample:

class Base
class << self
attr :my_name, true
end

def show_name
self.class.my_name
end
end

class Maker
def Maker.create_class(class_name)
Class.new(Base) { self.my_name = class_name }
end
end

HEH = Maker.create_class("HEH")

heh_instance = HEH.new
p heh_instance.kind_of?(Base)
p heh_instance.show_name

class ExtendedHEH < HEH
end

p ExtendedHEH.new.show_name

I want the last 'p' to print out "HEH". I understand why Base.show_name
is not working for the extended class (self resolves to itself, which will grab the extended class 'ExtendedHEH')... but I do not understand how I can access
the singleton class to get at "HEH". Any thoughts?

-Tom
 
T

ts

T> class Base
T> class << self
T> attr :my_name, true

def inherited(kl)
kl.my_name = self.my_name unless kl.my_name
super
end

T> end


Guy Decoux
 
T

Thomas E Enebo

Thanks! I have a strange variation on this (using 'inherited') that works
but yours is much cleaner :)

-Tom
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,020
Latest member
GenesisGai

Latest Threads

Top