Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • Removing/undefining a class method
  • http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/15408
  • http://split-s.blogspot.com/2006/01/removing-methods-from-module.html
like image 375
codecraig Avatar asked Feb 23 '23 20:02

codecraig


1 Answers

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

like image 95
Michael Kohl Avatar answered May 10 '23 10:05

Michael Kohl