extend 擴(kuò)展
先來(lái)看兩段代碼
module Mod
def hello
puts 'hello for module Mod'
end
end
class Klass
def hello
puts 'hello for class klass'
end
end
k = Klass.new
k.hello #hello for class klass
puts k #<Klass:0x007f9e5a86ed90>
k.extend(Mod)
k.hello #hello for module Mod
puts k #<Klass:0x007f9e5a86ed90>
module Mod
def hello
puts 'hello for module Mod'
end
end
class Klass
self.extend Mod
def hello
puts 'hello for class klass'
end
end
k = Klass.new
k.hello #hello for class klass
Klass.hello #hello for module Mod
- extend 是針對(duì)object的擴(kuò)展(因?yàn)閏lass本身也是一個(gè)object)或者說(shuō)是 類方法危虱?
- extend 插入的祖先鏈低于object的class 所以Mod里面的hello被先調(diào)用
include 帶入
#!/usr/bin/env ruby
module Mod
def hello
puts 'Mod\'s hello'
end
class << self
def included(base)
def base.call
puts 'base call'
end
base.extend ClassMethods
end
end
module ClassMethods
def hi
puts 'hi'
end
end
end
class Test
include Mod
end
Test.hi #hi
Test.call #base call
Test.new.hello #Mod's hello
針對(duì)那個(gè)extend丽惶。 可以說(shuō)include 一般是被 class 用的 實(shí)例方法?
最后ruby2.0開始引入prepend 作用類似于include 只不過(guò)祖先鏈處于接收者本身下面
module M
def test_method
puts 'this is test'
end
def anthor_method
puts 'anthor_method'
end
end
class C
include M
end
class AnotherC
extend M
end
C.new.test_method #this is test
AnotherC.anthor_method #anthor_method
Over