Is there a way to avoid defining a method with a specific name?

Is there a way to avoid (raise an error when trying) to define a method with a specific name, for example Foo#bar ? (Usekasa will be when Foo#bar already defined, and I want this method to be overridden, but this is not relevant to the question.) I assume 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
source share
2 answers

Perhaps you can catch the callback in the method_added( ) of the Module class and check the method name and remove the added method if it does not meet your criteria. Then you can cause an error.

Not exactly, but close enough, I think.

 class Class def method_added(method_name) if method_name == :bar remove_method :bar puts "#{method_name} cannot be added to #{self}" end end 
+4
source
 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 
+5
source

Source: https://habr.com/ru/post/1480816/


All Articles