ようへいの日々精進XP

よかろうもん

2018 年 02 月 18 日(日)

ジョギング

  • 香椎浜 x 5
  • 気候的に走りやすかったので, 5 周頑張ってみた
  • 後半は自分が思っているよりも体が動いていなくて辛かった

日課

  • (腕立て x 50 + 腹筋 x 30) x 3

夕飯

  • 奥さんが角煮作りを頑張っている
  • ゆで卵が崩壊していた

今日のるびぃ ~ Refinement (2) ~

これは メタプログラミング Ruby 第 2 版 の読書メモです.

Refinement の中で出来ること

Refinement の中で出来ること.

  • 既存のメソッドの再定義
  • モジュールの include や prepend
module Mod1
  def method
    'Mod1#method'
  end
end

class Cls1
  def method
    'Cls1#method'
  end
end

module Mod1Refine
  refine Cls1 do
    def method
      'Refined_Mod1#method'
    end
  end
end

p Cls1.new.method #=> "Cls1#method"
using Mod1Refine
p Cls1.new.method #=> "Refined_Mod1#method"

Refinement が有効になっているコードの優先度

Refinement が有効になっているコードの優先度.

module Mod1
  def method
    'Mod1#method'
  end
end

class Cls1
  prepend Mod1
  def method
    'Cls1#method'
  end
end

module Mod1Refine
  refine Cls1 do
    def method
      'Refined_Mod1#method'
    end
  end
end

p Cls1.new.method #=> "Mod1#method"
using Mod1Refine
p Cls1.new.method #=> "Refined_Mod1#method"
  • リファインされた側のコードよりも優先される
  • include や prepend したモジュールのコードよりも優先される

Refinement の抜け道

class Cls1
  def method1
    'Cls1#method1'
  end

  def method2
    method1
  end
end

module Mod1Refine
  refine Cls1 do
    def method1
      'Refined#method1'
    end
  end
end

p Cls1.new.method1 #=> "Cls1#method1"
p Cls1.new.method2 #=> "Cls1#method1"

using Mod1Refine
p Cls1.new.method1 #=> "Refined#method1"
p Cls1.new.method2 #=> "Cls1#method1"

Cls1#method1 は refine している筈なのに... Cls1#method1 が返ってきている.

参考

ふむふむ.