Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to undefine class in Ruby?

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.

I have to undefine an ActiveRecord Model, run two lines of code, and restore the model back to its original form.

The problem is, I have an model Contact and I am using a company's API and it happens that they have some class called Contact, and changing my model name would be lot of work for me.

What can I do in this situation?

like image 476
Bhushan Lodha Avatar asked Jul 16 '12 11:07

Bhushan Lodha


People also ask

How do you Undefine a method in Ruby?

Ruby provides a special keyword which is known as undef keyword. This keyword used to avoid the current working class from responding to calls to the specified named methods or variable. Or in other words, once you use under keyword with any method name you are not able to call that method.

What does .first mean in Ruby?

The first() is an inbuilt method in Ruby returns an array of first X elements. If X is not mentioned, it returns the first element only. Syntax: range1.first(X) Parameters: The function accepts X which is the number of elements from the beginning. Return Value: It returns an array of first X elements.


1 Answers

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

like image 138
Lee Jarvis Avatar answered Sep 17 '22 04:09

Lee Jarvis