codecraig
codecraig

Reputation: 3158

Removing/undefining a class method that's included by another module

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:

Upvotes: 4

Views: 1669

Answers (1)

Michael Kohl
Michael Kohl

Reputation: 66837

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

Upvotes: 8

Related Questions