Skip to main content

Command Palette

Search for a command to run...

Remove Nested module constant in ruby

Updated
1 min read

You might have seen this solution.

Object.send(:remove_const, :ExampleClass)

But what if you want to remove namespaced classes in Ruby. You can use the same method, but instead of Object use the parent module where your class is nested.

module App
  module ExampleClass
  end 
end 

Object.send(:remove_const, :App::ExampleClass) ### ❌ Does not work!!!!

App.send(:remove_const, :ExampleClass) # ✅ This works

Now before removing the const, you can check if the constant is defined or not.

if App.const_defined?(:ExampleClass)
  App.send(:remove_const, :ExampleClass)
end

Perfect! 🍄

50 views
How to remove or undefine namespaced constant in ruby