LoginSignup
2
1

More than 5 years have passed since last update.

rubyでpatch

Last updated at Posted at 2017-07-18

patch

どこかのコードで面白いpatchの当て方をしていたので備忘録がわりに残しとこうかと思います。

前提条件

  • patchしたいクラス及びmoduleをrequireできていること

コード

test.rb
class Test
  def test i
    !i.nil?
  end
end
test2.rb
require_relative './test'
class Test
  alias test2 test

  def test i=nil
    test2(i) || 'hello test2'
  end
end

require_relative './test2'
p Test.new.test
p Test.new.test 'test'
output
hello test2
true

testばっかりでなんやねんという感じですが、上手いことTest classを使っているところに、test2.rbを噛ませてやれば、test2.rbで定義したtest関数が実行されるわけですね。

aliasについて蛇足の解説

alias 新メソッド名 旧メソッド名

と定義してpatchを当てたい関数を一旦別名で宣言することができる。
その後旧メソッドをオーバーライドしても新メソッドが以前の中身を保持しているため新メソッド内で旧メソッドを呼び出す事ができたりする。

alias_methodの方が色々制御できるっぽい。
後これ書いている内に色々と調査していたら結構普通の使い方らしい
http://ref.xaio.jp/ruby/classes/module/alias_method

2
1
1

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