zuba
zuba

Reputation: 1508

How to undefine namespaced class in Ruby?

I can undefine Bar (How to undefine class in Ruby?), but how to undefine Foo::Bar ?

irb(main):266:0> Object.send :remove_const, :ActiveRecord::Base
TypeError: :ActiveRecord is not a class/module

irb(main):267:0> Object.send :remove_const, :"ActiveRecord::Base"
NameError: `ActiveRecord::Base' is not allowed as a constant name

irb(main):269:0> module ActiveRecord; Object.send :remove_const, :Base; end
NameError: constant Object::Base not defined

Upvotes: 4

Views: 1494

Answers (1)

Holger Just
Holger Just

Reputation: 55758

Constants are defined in their respective parent module, with top-level constants being defined on the Object class.

Thus, ActiveRecord::Base is a constant(Base) which is defined on the ActiveRecord module. Now, in order to remove this constant, you have to call the remove_const method on the ActiveRecord module:

ActiveRecord.send(:remove_const, :Base)

Alternatively, you could also traverse the path directly from Object, i.e.

Object.const_get(:ActiveRecord).send(:remove_const, :Base)

Upvotes: 11

Related Questions