まとめ
- prependしたクラスの挙動の前後に、処理を追加したい
- prependしたクラスの挙動を完全に上書きしたい
1. prependしたクラスの挙動の前後に、処理を追加したい
モンキーパッチではこのパターンがよく使われている。
module Hoge
def execute
pp 'モジュール'
super
end
end
class Human
def execute
pp 'クラス'
end
end
Human.prepend(Hoge)
Human.ancestors
=> [Hoge, Human, ....]
Human.new.execute
#=>
'モジュール'
'クラス'
2. prependしたクラスの挙動を完全に上書きしたい
module Hoge
def execute
pp 'モジュール'
end
end
class Human
def execute
pp 'クラス'
end
end
Human.prepend(Hoge)
Human.ancestors
=> [Hoge, Human, ....]
Human.new.execute
#=>
'モジュール'
2'. prependしたクラスの挙動を完全に上書きしたい -> includeではダメ
module Hoge
def execute
pp 'モジュール'
end
end
class Human
include Hoge
def execute
pp 'クラス'
end
end
Human.ancestors
=> [Human, Hoge, ....]
Human.new.execute
#=>
'クラス'
おまけ: 継承している場合
superを呼ぶと、Humanだけでなく、Humanの親クラスであるAnimalまで探索される。
module Hoge
def execute
pp 'モジュール'
super
end
end
class Animal
def execute
pp '親クラス'
end
end
class Human < Animal
end
Human.prepend(Hoge)
Human.ancestors
=> [Hoge, Human, Animal, ....]
Human.new.execute
#=>
'モジュール'
'親クラス'
参考