ruby聲明式語法的實(shí)現(xiàn)例子
在ActiveRecord可以用很方便的聲明方式來定義model之間的關(guān)聯(lián)關(guān)系,例如:
class Topic < ActiveRecord::Base
has_many :posts
belongs_to :user
end
has_many和belongs_to其實(shí)是Topic類的class method,標(biāo)準(zhǔn)寫法是:
class Topic < ActiveRecord::Base
Topic.has_many(:posts)
Topic.belongs_to(:user)
end
那么has_many可以給我們帶來什么呢?類方法has_many在被執(zhí)行的時候,給Topic的對象實(shí)例添加了一系列方法:posts, posts<<, orders.push......等等。所以當(dāng)我們在model里面聲明has_many,belongs_to等對象關(guān)系的時候,一系列相關(guān)的對象方法就被自動添加進(jìn)來了。 讓我們來自己試試看吧:
module M
def self.included(c)
c.extend(G)
end
module G
def generate_method(*args)
args.each do |method_name|
define_method(method_name) { puts method_name }
end
end
end
end
class C
include M
generate_method :method1, :method2
end
c = C.new
c.method1
c.method2
我們定義了一個聲明generate_method,可以接受多個symbol,來動態(tài)的創(chuàng)建同名的方法?,F(xiàn)在我們在類C里面使用這個聲明:generate_method :method1, :method2,當(dāng)然我們需要include模塊M。為什么ActiveRecord的model不需要include相關(guān)的模塊呢?當(dāng)然是因?yàn)門opic的父類ActiveRecord::Base已經(jīng)include了模塊Associations了。
類C通過include模塊M,調(diào)用了模塊M的一個included回調(diào)接口,讓類C去extend模塊G,換句話來說就是,通過include模塊M,來給類C動態(tài)添加一個類方法generate_method。
這個generate_method被定義在模塊G當(dāng)中,它接受一系列參數(shù),來動態(tài)創(chuàng)建相關(guān)的方法。于是我們就實(shí)現(xiàn)了這樣的DSL功能:
通過在類C里面聲明generate_method :method1, :method2,讓類C動態(tài)的添加了兩個實(shí)例方法method1,method2,是不是很有意思? 實(shí)際上rails的對象關(guān)聯(lián)聲明也是以同樣的方式實(shí)現(xiàn)的。
相關(guān)文章
Ruby中Hash哈希結(jié)構(gòu)的基本操作方法小結(jié)
Hash是一種鍵值對應(yīng)的數(shù)據(jù)結(jié)構(gòu),Ruby中直接帶有Hash類來對其提供支持,這里我們整理了Ruby中Hash哈希結(jié)構(gòu)的基本操作方法小結(jié),首先來回顧一下Hash的基本知識:2016-06-06
使用Ruby re模塊創(chuàng)建復(fù)雜的正則表達(dá)式
復(fù)雜的正則表達(dá)式很難構(gòu)建,甚至很難閱讀。Ruby的Re模塊可以幫助你利用簡單的表達(dá)式構(gòu)建復(fù)雜的正則表達(dá)式2014-03-03
Ruby的字符串與數(shù)組求最大值的相關(guān)問題討論
這篇文章主要介紹了Ruby中的字符串與數(shù)組求最大值的相關(guān)問題,文中還提到了sort排序方法的相關(guān)用法,需要的朋友可以參考下2016-03-03
Ruby實(shí)現(xiàn)的刪除已經(jīng)合并的git分支腳本分享
這篇文章主要介紹了Ruby實(shí)現(xiàn)的刪除已經(jīng)合并的git分支腳本分享,本文給出腳本代碼、使用方法和執(zhí)行結(jié)果,需要的朋友可以參考下2015-01-01

