4

有没有办法避免(尝试时引发错误)定义具有特定名称的方法,例如Foo#bar?(一个用例是 whenFoo#bar已经定义,我想避免该方法被覆盖,但这与问题无关。)我假设如下:

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 回答