Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to avoid definition of a method with a certain name?

Tags:

methods

ruby

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
like image 928
sawa Avatar asked Jan 13 '23 09:01

sawa


1 Answers

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
like image 190
Shawn Balestracci Avatar answered Jan 23 '23 06:01

Shawn Balestracci