简体   繁体   中英

Ruby Class Inheritance: How to preven a public method from beeing overwritten in the child classes

Is it possible to prevent a public method from being overwritten in the child classes?

class Parent
  def some_method
     #important stuff that should never be overwritten
  end
end

class Child < Parent
  def some_method
     #should not be possible to overwrite (raise an error if a child class tries to do it)
  end
end

Thanks!

You can use 'method_added' and 'inherited' hook for this purpose:

class Foo
  def self.inherited(sub)
    sub.class_eval do
      def self.method_added(name)
        if name == :some_method
          remove_method name
          raise Exception, "Can't override #{name} method"
        end
      end
    end
  end
end

class Bar < Foo
end

class Bar
  def some_method
  end
end
# => Exception: Can't override some_method method

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM