【Ruby】Goldリベンジするぞ-メタプロ番外編フックメソッド
フックメソッド。初めて聞きました。
サンプルサンプル〜
class String def self.inherited(subclass) puts "#{self}→#{subclass}" end end class MyClass < String; end #=>String→MyClass
このサンプルのinheritedのように特定のイベントをキャッチしてその時の動作を記述しておくメソッドのようです。公式教科書に載ってなかったですけど普通に出題されました。(もちろんわからなかった…。)出題されたのは以下のメソッド(だったと思う)。
module Feature def self.append_features(klass) p klass.ancestors #=> [Container, Object, Kernel, BasicObject] super end end class Container include Feature p ancestors #=> [Container, Feature, Object, Kernel, BasicObject] end
includeメソッド(Container.include(Feature))を使うとmodule側のappend_features(Feature.append_features(Container))を呼ぶわけです。そのためかappend_featuresの中のsuperを消すとmixinできなくなってしまいます。includedは継承で言うところのinheritedと同じような動作をします。同じようにextend-extended-extend_objectも覚えておくと出題されるかも。inheritedには同じようなメソッドはないんでしょうか。includeやextendを直接書き換える方法もある。
他にも保持するメソッドが変化した時の処理はmethod_added、method_removed、method_undefinedで追加できます。super呼ばないほう。
Goldはなかなか大変!!