module NewMethod
def self.included(mod)
mod.class_eval do
alias_method_chain :method, :new_method
end
end
def method_with_new_method
method_without_new_method
'new method'
end
end
class Origin
def method
'origin method'
end
include NewMethod
end
puts Origin.new.method #=> new method
include をメソッドの後に書かないといけないのが微妙
ちょっと補足
module NewMethod
def method
'new method'
end
end
class Origin
include NewMethod
end
puts Origin.new.method # => new method
モジュールのメソッドは呼ばれない.
module NewMethod
def method
'new method'
end
end
class Origin
include NewMethod
def method
'origin method'
end
end
puts Origin.new.method # => origin method
メソッドの定義順を変えても駄目.
module NewMethod
def method
'new method'
end
end
class Origin
def method
'origin method'
end
include NewMethod
end
puts Origin.new.method # => origin method
結局,include しても,最初に見つかるメソッドが呼ばれるだけ.
ということで,冒頭のコードのように method_chain を使って定義.