Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
734 views
in Technique[技术] by (71.8m points)

ruby - Remove/undef a class method

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)

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.

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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)

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,
  • Foo.singleton_class,
  • class Foo; class << self which is commonly use to define class methods.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...