Rubyの子クラスで定数を再定義したのに親の定数が参照されちゃう
ちゃう
class Parent CONST = 'parent' def initialize p CONST end end class Child1 < Parent CONST = 'child' end Child1.new # "parent"
"child"を期待してたら、"parent"が返ってきた!?
定数の場合、今のスコープになかったら、外のスコープから探索するので initializeメソッドの外に出たら、Parent::CONSTがいるので、その値を返しているみたい。
じゃあ、子クラス毎にinitializeメソッドを定義すれば
class Parent CONST = 'parent' end class Child1 < Parent CONST = 'child' def initialize p CONST end end Child1.new # "child"
やりました、期待通り"child"が返ってきました!
ないな
要は 子クラス::CONST を参照してくれれば良いのでしょ
class Parent CONST = 'parent' def initialize p self.class::CONST end end class Child1 < Parent CONST = 'child' end Child1.new # "child"
いけそう
class Parent CONST = 'parent' def initialize p self.class::CONST end end class Child2 < Parent; end Child2.new # "parent"
さらに、継承しても
class Parent CONST = 'parent' def initialize p self.class::CONST end end class Child2 < Parent; end class Grandchild < Child2 CONST = 'grandchild' end Grandchild.new # "grandchild"
期待通り!