Ruby类继承:如何防止子类中的公共方法被覆盖

时间:2011-10-20 10:43:48

标签: ruby ruby-on-rails-3 inheritance multiple-inheritance single-table-inheritance

是否可以防止在子类中覆盖公共方法?

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

谢谢!

1 个答案:

答案 0 :(得分:7)

您可以使用'method_added'和'inherited'钩子来实现此目的:

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