如何在Ruby中取消定义类?定义、如何在、Ruby

2023-09-08 15:44:15 作者:青春年少必须狂

取消定义在Ruby中的方法是pretty的简单,我可以只使用民主基金METHOD_NAME

有什么相似的一类?我在 MRI 1.9.2

我要取消定义一个ActiveRecord模式,运行两行code和恢复模式恢复到原来的形态。

现在的问题是,我有一个模型联系方式和我使用的是公司的API和它发生,他们有一些类叫做联系人,并改变了我的型号名称将是大量的工作对我来说。

我可以做这种情况呢?

解决方案

 >>类Foo;结束
=>零
>> Object.constants.include?(:富)
=>真正
>> Object.send(:remove_const,:富)
=>富
>> Object.constants.include?(:富)
=>假
>>富
NameError:未初始化恒富
 

修改只注意到你的编辑,删除常数可能不是达到你所要寻找的最好的方式。为什么不只是移动的联系方式类一成不同的命名空间。

EDIT2 您也可以临时重命名你的类是这样的:

 类Foo
  高清栏
    '这里'
  结束
结束

TemporaryFoo =富
Object.send(:remove_const,:富)
#做一些东西
富= TemporaryFoo
Foo.new.bar#=> 这里
 

此外,与此麻烦的是你仍然有新的联系方式类,所以你必须删除了。我真的建议名称间距你的类来代替。这也将帮助你避免任何加载问题

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?

解决方案

>> 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