LoginSignup
1
0

More than 3 years have passed since last update.

【Ruby】prependの使い道

Last updated at Posted at 2019-07-14

まとめ

  1. prependしたクラスの挙動の前後に、処理を追加したい
  2. 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
#=> 
'モジュール'
'親クラス'

参考

共同編集者

@popmac

1
0
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
1
0