简体   繁体   English

如何使用类<< self eigenclass模式从ruby中的类动态删除remove_method?

[英]How can I dynamically remove_method from class in ruby using class << self eigenclass pattern?

I'm trying to dynamically undefine a method by opening up the eigenclass of the class. 我试图通过打开类的本征类来动态地取消定义方法。 I want something like: 我想要类似的东西:

def remove_defined_mock_name_method(name)
  if Settings.respond_to?(name)
    class << Settings
      remove_method name
    end
  end
end

where 'name' is a symbol. 其中“名称”是一个符号。 Problem is name is not available to the reopened class. 问题是名称对于重新打开的类不可用。 How can I achieve undefining a class method dynamically like this through a method call? 如何通过方法调用动态地实现未定义类方法的定义?

For those curious, the use case is that I want to undefine a dynamically defined method after each test in rspec for rails. 对于那些好奇的人,用例是我想在rspec的每个测试中为rails取消定义动态定义的方法。

name is a local variable. name是局部变量。 Local variables are local to the scope they are defined in, that's why they are called local variables. 局部变量对于定义它们的作用域是局部的,这就是为什么它们被称为局部变量。 The only construct in Ruby that creates a nested scope is a block, so you would have to use a block if you want to have access to name , ie by using class_eval or something like that. Ruby中唯一创建嵌套作用域的构造是一个块,因此,如果要访问name ,即使用class_eval或类似的东西,就必须使用一个块。

But in this case, that's not necessary: 但是在这种情况下,这不是必需的:

def remove_defined_mock_name_method(name)
  Settings.singleton_class.send(:remove_method, name) if Settings.respond_to?(name)
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM