prependとmoduleとalias_method_chain

モンキーパッチしてて、ふと思ったこと。

module Patch
  def x
    [:Patch, super]
  end
end

module Foo
  def x
    [:Foo]
  end
end

class Bar
  include Foo
  def x
    [:Bar, super]
  end
end

module Foo
  prepend Patch
end

class Baz
  include Foo
  def x
    [:Baz, super]
  end
end

Bar.ancestors #=> [Bar, Foo, Object, PP::ObjectMixin, Kernel, BasicObject]
Bar.new.x #=> [:Bar, [:Foo]]

Baz.ancestors #=> [Baz, Patch, Foo, Object, PP::ObjectMixin, Kernel, BasicObject]
Baz.new.x #=> [:Baz, [:Patch, [:Foo]]]

そりゃそうかっていえばそんな気もするし、引っかかりそうだっていえばばそんな気もする、ような。BarとBazを同じ状態にできないのかっていうと、まあ、できるみたい。

class Bar
  include Foo
end
Bar.ancestors #=> [Bar, Patch, Foo, Object, PP::ObjectMixin, Kernel, BasicObject]
Bar.new.x #=> [:Bar, [:Patch, [:Foo]]]

ふむー。