How to undefine class in Ruby?

后端 未结 2 589
春和景丽
春和景丽 2020-12-03 02:48

Undefining a method in Ruby is pretty simple, I can just use undef METHOD_NAME.

Is there anything similar for a class? I am on MRI 1.9.2. <

2条回答
  •  感情败类
    2020-12-03 03:14

    class Foo; end
    # => nil
    Object.constants.include?(:Foo)
    # => true
    Object.send(:remove_const, :Foo)
    # => Foo
    Object.constants.include?(:Foo)
    # => false
    Foo
    # NameError: uninitialized constant Foo
    

    EDIT Just noticed your edit, removing the constant is probably not the best way to achieve what you're looking for. Why not just move one of the Contact classes into a separate namespace.

    EDIT2 You could also rename your class temporarily like this:

    class Foo
      def bar
        'here'
      end
    end
    
    TemporaryFoo = Foo
    Object.send(:remove_const, :Foo)
    # do some stuff
    Foo = TemporaryFoo
    Foo.new.bar #=> "here"
    

    Again, the trouble with this is that you'll still have the newer Contact class so you'll have to remove that again. I would really recommend name-spacing your classes instead. This will also help you avoid any loading issues

提交回复
热议问题