2010-12-10 41 views
2

我正在尋找一個簡單的例子,說明如何使用Ruby和正則表達式模式匹配來編寫內部DSL。類似西納特拉如何處理路線如何使用Ruby + Regex編寫內部自然語言DSL?

get '/say/*/to/*' do 
    # Some Ruby code here 
end 

類似的還有黃瓜是如何處理的步驟定義:

Given /^I have (\d+) cucumbers in my belly$/ do |cukes| 
    # Some Ruby code here 
end 

我在商不感興趣,或流利的方法鏈接。基本上我想要一個Ruby類,它看起來是這樣的:

class SpecVocabulary 

    match ‘pattern’ do 
     # Some Ruby code here 
    end 

    # Or, using a different keyword 
    phrase ‘pattern’ do 
     # Some Ruby code here 
    end 
end 

我掙扎什麼是配線起來這使得SpecVocabular類自動匹配模式並填寫其數據的代碼。

我希望有人有一個簡單的例子來說明如何做到這一點,我試圖避免必須在Sinatra和黃瓜的源代碼中潛水。

順便說一句,我已經有自然語言定義,但我故意省略它。

回答

1

下面是關於在Ruby中創建領域特定語言的綜合博客文章:

http://www.daniel-azuma.com/blog/view/z3bqa0t01uugg1/implementing_dsl_blocks

順便說一句,這是不常見的一類中使用你的DSL,我想它寧願像:

vocabulary :SpecVocabulary do 
    match 'pattern' do 
    # Some Ruby code here 
    end 

    # Or, using a different keyword 
    phrase 'pattern' do 
    # Some Ruby code here 
    end 
end