淺談Ruby on Rails中的include和extend
從模塊引入方法、變量,使得編程變得簡單,擴展性愈強,比以往的類的繼承更靈活。這樣的引入,仿佛將一個方法塊,復制了一份放到了你所引用的類或者模塊里面。你完全可以將多個互不相干的類中相同的方法拿出來寫到一個模塊中,這樣可以使得代碼精簡,符合Ruby的設計初衷,而且,使得你的程序更有條理。
Ruby on Rails常見用法
通常引用模塊有以下3種情況:
1.在類定義中引入模塊,使模塊中的方法成為類的實例方法
這種情況是最常見的
直接 include
2.在類定義中引入模塊,使模塊中的方法成為類的類方法
這種情況也是比較常見的
直接 extend
3.在類定義中引入模塊,既希望引入實例方法,也希望引入類方法
這個時候需要使用 include,
但是在模塊中對類方法的定義有不同,定義出現在self.included塊中
def self.included(c) ... end 中
Ruby on Rails實例講解
Code
- #基類
- module Base
- #顯示
- def show
- puts "You came here!"
- end
- end
- class Car
- extend Base #擴展了類方法,我們可以通過Car.show調用
- end
- class Bus
- include Base #擴展了實例方法,可以通過Bus.new.show調用
- end
但是我們經常有這樣的需要,希望基類足夠強大,既可以擴展實例方法,也可以擴展類方法,Ruby on Rails同樣提供了解決方案。
- Code
- #基類
- module Base
- def show
- puts "You came here!"
- end
- #擴展類方法
- def self.included(base)
- def base.call
- puts "I'm strong!"
- end
- base.extend(ClassMethods)
- end
- #類方法
- module ClassMethods
- def hello
- puts "Hello baby!"
- end
- end
- end
- class Bus
- include Base
- end
此時Bus已經具備了實例方法show,類方法:call 、hello,訪問方式
- Bus.new.show
- Bus.call
- Bus.hello
肯定也有人提出此類疑問,使用extend能夠實現此功能不?
答案是:暫未找到,如您找到請明示,多謝!
我也曾經做過以下實驗,結果沒有成功,在此也張貼出來,希望能給您帶來一些啟示。
- Code
- #基類
- module Base
- def show
- puts "You came here!"
- end
- #擴展實例方法
- def self.extended(base)
- base.extend(InstanceMethods)
- end
- module InstanceMethods
- def love
- puts 'We are instances,loving each other!'
- end
- end
- end
- class Car
- extend Base
- end
但是這樣,實例方法擴展失敗,依然擴展了類方法
- Car.show
- Car.love #類方法
- Car.new.love #undefined method 'love'
【編輯推薦】