4

Is there a way to avoid (raise an error when it is attempted) definition of a method with a certain name, for example Foo#bar? (A usecase would be when Foo#bar is already defined, and I want to avoid that method being overridden, but that is irrelevant to the question.) I am assuming something like:

class Foo
  prohibit_definition :bar
end

...
# Later in some code

class Foo
  def bar
    ...
  end
end
# => Error: `Foo#bar' cannot be defined
4

2 に答える 2

5
class Class
  def method_added(method_name)
    raise "So sad, you can't add" if method_name == :bad
  end
end

class Foo
  def bad
    puts "Oh yeah!"
  end
end

#irb> RuntimeError: So sad, you can't add
#   from (irb):3:in `method_added'
#   from (irb):7
于 2013-05-14T23:00:43.330 に答える
4

おそらく、クラスmethod_added(の ) でコールバックをキャッチしModule、メソッド名を確認して、基準を満たさない場合は追加されたメソッドを削除できます。次に、エラーを発生させることができます。

あなたは正確に望んでいませんが、十分に近いと思います。

class Class
  def method_added(method_name)
    if method_name == :bar
        remove_method :bar
        puts "#{method_name} cannot be added to #{self}"
  end
end
于 2013-05-14T22:56:28.390 に答える