LoginSignup
3
3

More than 5 years have passed since last update.

継承したメソッドをオーバーライドさせない方法

Posted at

とあるクラスを継承した時にオーバーライド不可にさせる。
今回は使い方の問題もあり、定義済みの全メソッドをオーバーライドさせない。というかしたらErrorを出すようにする。

コード


class ParentClass
  def self.method_added(name)
    if self == ParentClass
      return
    end

    if ParentClass.instance_eval { method_defined?(name) }
      remove_method(name)
      raise TypeError, "do not Override the methods."
    end
  end

  def hello
    puts "Hello World."
  end
end

class ChildClass < ParentClass
  def hello
    puts "Goodbye World."
  end
end

obj = ParentClass.new
obj.hello

obj = ChildClass.new # Error
obj.hello

解説

method_added

これがメソッドが追加された「直後」に呼ばれるメソッド。
なので、このタイミングでメソッドがあるかどうかを検査すると、必ず「存在する」状態になります。

なので、

if self == ParentClass
  return
end

で、省いています。

instance_eval

instance_evalは渡したブロックを指定したクラスのオブジェクト内で実行するメソッドです。
なので、最終的な検査は

ParentClass.instance_eval { method_defined?(name) }

これでとりあえずOKっぽいです。

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3