删除/取消定义类方法 [英] Remove/undef a class method

查看:58
本文介绍了删除/取消定义类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您可以像这样为类动态定义类方法:

You can dynamically define a class method for a class like so:

class Foo
end

bar = %q{def bar() "bar!" end}
Foo.instance_eval(bar)

但是你如何做相反的事情:删除/取消定义一个类方法?我怀疑 Module 的 remove_methodundef_method 方法可能能够用于此目的,但我在谷歌搜索数小时后看到的所有示例都用于删除/取消定义实例方法,而不是类方法.或者,您也可以将语法传递给 instance_eval 来执行此操作.

But how do you do the opposite: remove/undefine a class method? I suspect Module's remove_method and undef_method methods might be able to be used for this purpose, but all of the examples I've seen after Googling for hours have been for removing/undefining instance methods, not class methods. Or perhaps there's a syntax you can pass to instance_eval to do this as well.

提前致谢.

推荐答案

class Foo
  def self.bar
    puts "bar"
  end
end

Foo.bar    # => bar

class <<Foo
  undef_method :bar
end
# or
class Foo
  singleton_class.undef_method :bar
end

Foo.bar    # => undefined method `bar' for Foo:Class (NoMethodError)

当你定义一个像 Foo.bar 这样的类方法时,Ruby 把它当作 Foo 的单例类.Ruby 不能将它放在 Foo 中,因为那样它将是一个实例方法.Ruby 创建 Foo 的单例类,将单例类的超类设置为 Foo 的超类,然后将 Foo 的超类设置为单例类:

When you define a class method like Foo.bar, Ruby puts it Foo's singleton class. Ruby can't put it in Foo, because then it would be an instance method. Ruby creates Foo's singleton class, sets the superclass of the singleton class to Foo's superclass, and then sets Foo's superclass to the singleton class:

Foo -------------> Foo(singleton class) -------------> Object
        super      def bar             super

有几种方法可以访问单例类:

There are a few ways to access the singleton class:

  • class <<,
  • Foo.singleton_class,
  • class Foo;类< 通常用于定义类方法.
  • class <<Foo,
  • Foo.singleton_class,
  • class Foo; class << self which is commonly use to define class methods.

注意我们使用了undef_method,我们也可以使用remove_method.前者阻止对方法的任何调用,后者只删除当前方法,如果存在则回退到超级方法.有关详细信息,请参阅Module#undef_method.

Note that we used undef_method, we could have used remove_method. The former prevents any call to the method, and the latter only removes the current method, having a fallback to the super method if existing. See Module#undef_method for more information.

这篇关于删除/取消定义类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆