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

cod*_*aig 4 ruby metaprogramming

我想删除一个通过include函数添加到我的类的类方法.例如:

class Foo
    include HTTParty

    class << self
      remove_method :get
    end
end
Run Code Online (Sandbox Code Playgroud)

这不起作用,它说"get"不是Foo的方法.基本上,"get"方法是HTTParty模块提供的,我想删除它.我尝试了几次没有运气的尝试.我读过/试过的东西:

Mic*_*ohl 8

使用undef而不是remove_method:

require 'httparty'

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

Foo.get #=> NoMethodError: undefined method `get' for Foo:Class
Run Code Online (Sandbox Code Playgroud)

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