Ruby DSL特點分析介紹
Ruby語言是一個應用靈活的解釋型腳本語言。對于一個編程人員來說,Ruby DSL是一個功能強大的工具。下面我們就來一起看看Ruby DSL特點介紹。#t#
在rails里面,我們可以用很方便的聲明方式來定義model之間的關聯(lián)關系,Ruby DSL特點例如:
- class Topic < Active
Record::Base - has_many :posts
- belongs_to :user
- end
- class Topic < Active
Record::Base - has_many :posts
- belongs_to :user
- end
那has_many和belongs_to究竟是什么東西呢?其實他們是Topic類的class method,Ruby DSL特點的標準寫法是:
- class Topic < ActiveRecord::Base
- Topic.has_many(:posts)
- Topic.belongs_to(:user)
- end
- class Topic < ActiveRecord::Base
- Topic.has_many(:posts)
- Topic.belongs_to(:user)
- end
那么has_many可以給我們帶來什么呢?類方法has_many在被執(zhí)行的時候,給Topic的對象實例添加了一系列方法:posts, posts<<, orders.push......等等。所以當我們在model里面聲明has_many,belongs_to等對象關系的時候,一系列相關的對象方法就被自動添加進來了。
既然明白了rails的小把戲,讓我們來自己試試看吧:
- 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
- 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,當然我們需要include模塊M。為什么rails的model不需要include相關的模塊呢?當然是因為Topic的父類ActiveRecord::Base已經include了模塊Associations了。
類C通過include模塊M,調用了模塊M的一個included回調接口,讓類C去extend模塊G,換句話來說就是,通過include模塊M,來給類C動態(tài)添加一個類方法generate_method。
這個generate_method被定義在模塊G當中,它接受一系列參數(shù),來動態(tài)創(chuàng)建相關的方法。于是我們就實現(xiàn)了這樣的DSL功能:
通過在類C里面聲明generate_method :method1, :method2,讓類C動態(tài)的添加了兩個實例方法method1,method2,是不是很有意思?
實際上rails的對象關聯(lián)聲明也是以同樣的方式實現(xiàn)的。
以上就是對Ruby DSL特點的分析介紹。