Redefine a class with same name

M

Martin Boese

Is there any way to to remove the definition of a class so I can reuse its
name? Like below I'd like to reuse the name 'A' but since it's already
defined with a different superclass I get a 'TypeError: superclass mismatch
for class A'.

------------------------------------------------------

class X
end
class Y
end

class A < X
end

==> Here I'd like to remove A's definition so I can:

class A < Y
end

==> without getting a: 'TypeError: superclass mismatch for class A'
 
R

Rick DeNatale

M> Is there any way to to remove the definition of a class so I can reuse its
M> name? Like below I'd like to reuse the name 'A' but since it's already
M> defined with a different superclass I get a 'TypeError: superclass mismatch
M> for class A'.

Just remove the constant

M> class A < X
M> end

Object.send:)remove_const, :A)

M> class A < Y
M> end

Keep in mind though, that this only removes the binding between the
constant and the class, it doesn't actually allow you to change the
old class, and any existing instances will still be instances of the
old class not the new one:

k$ irb
irb(main):001:0> class A
irb(main):002:1> def foo
irb(main):003:2> end
irb(main):004:1> end
=> nil
irb(main):005:0> a = A.new
=> #<A:0x6e578>
irb(main):006:0> a.foo
=> nil
irb(main):007:0> Object.send:)remove_const, :A)
=> A
irb(main):008:0> a.foo
=> nil
irb(main):009:0> a.class
=> A
irb(main):010:0> A
NameError: uninitialized constant A
from (irb):10
irb(main):011:0> class A
irb(main):012:1> def bar
irb(main):013:2> end
irb(main):014:1> end
=> nil
irb(main):015:0> a.bar
NoMethodError: undefined method `bar' for #<A:0x6e578>
from (irb):15
irb(main):016:0>
 
M

Martin Boese

Excellent! That's fine for me. I only have the case for a web framework of
mine when using with fastcgi as different calls might use same class names
which I can unregister now.

Thanks,
martin
 

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,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top