删除/取消定义另一个模块包含的类方法

发布于 2024-12-06 18:25:54 字数 774 浏览 4 评论 0 原文

我想删除通过 include 函数添加到我的类中的类方法。例如:

class Foo
    include HTTParty

    class << self
      remove_method :get
    end
end

这不起作用,它说“get”不是 Foo 上的方法。基本上,“get”方法是由 HTTParty 模块提供的,我想将其删除。我已经尝试了几次但没有运气。我读过/尝试过的事情:

I'd like to remove a class method that gets added to my class via the include function. For example:

class Foo
    include HTTParty

    class << self
      remove_method :get
    end
end

This doesn't work, it says "get" isn't a method on Foo. Basically, the "get" method is provided the HTTParty module and I'd like to remove it. I've tried several attempts with no luck. Things I've read/tried:

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

乙白 2024-12-13 18:25:54

使用 undef 而不是 remove_method

require 'httparty'

class Foo
  include HTTParty
  class << self
    undef :get
  end
end

Foo.get #=> NoMethodError: undefined method `get' for Foo:Class

取消方法定义。 undef不能出现在方法中
身体。通过使用undef和alias,类的接口可以是
独立于超类进行修改,但请注意它可能会被破坏
程序通过内部方法调用self。
http://web.njit.edu/all_topics/Prog_Lang_Docs/html /ruby/syntax.html#undef

Use undef instead of remove_method:

require 'httparty'

class Foo
  include HTTParty
  class << self
    undef :get
  end
end

Foo.get #=> NoMethodError: undefined method `get' for Foo:Class

Cancels the method definition. Undef can not appear in the method
body. By using undef and alias, the interface of the class can be
modified independently from the superclass, but notice it may be broke
programs by the internal method call to self.
http://web.njit.edu/all_topics/Prog_Lang_Docs/html/ruby/syntax.html#undef

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文