2

Rubyで少し遊んでいる間、私は次のコードを書きました。

class A
end

A.singleton_class.instance_eval do
    undef_method :new
end

# or
# class << B
#   undef_method :new
# end

A.new

> NoMethodError: undefined method `new' for A:Class
>         from (irb):8
>         from /home/mmsequeira/.rvm/rubies/ruby-1.9.3-p327/bin/irb:16:in `<main>'

これはカッコいい。しかし、特定のクラスでどのメソッドが未定義であるかをどのように知ることができますか?

4

2 に答える 2

3

デフォルトではできません。メソッドの定義を解除すると、そのメソッドは存在しなくなります。ただし、削除されたときに記録することはできます。これは、メソッドフックを使用して実行し、すべてをキャプチャして、醜いエイリアスメソッドチェーンを回避できます。

class Module
  def method_undefined name
    (@undefined_methods ||= []) << name
  end

  def singleton_method_undefined name
    (@undefined_methods ||= []) << name
  end

  def undefined_methods
    @undefined_methods || []
  end
end

undef_methodこれにより、またはundef:を介して未定義のメソッドがキャプチャされます。

class C
  def foo; end
  def bar; end

  undef foo
  undef_method :bar
end

C.undefined_methods  #=> [:foo, :bar]
C.singleton_class.instance_eval { undef new }
C.singleton_class.undefined_methods  #=> [:new]

もちろん、何かをキャプチャする前に、モジュールにフックメソッドを含める必要があります。

于 2012-11-25T17:13:54.963 に答える
1

多分あなたは再定義する必要がありますModule#undef_method

class Module
  alias original_undef_method :undef_method
  @@undef_methods = {}
  def undef_method *methods
    methods.each{|method| @@undef_methods[[self, method]] ||= true}
    original_undef_method(*methods)
  end
  def self.undef_methods; @@undef_methods.keys end
end

次に、次のようになります。

class A
end
A.singleton_class.instance_eval do
    undef_method :new
end
Module.undef_methods
# => [[#<Class:A>, :new]]
于 2012-11-25T16:48:40.203 に答える