2011-12-12 74 views
2

我一直在學習Ruby並在一個自我項目中使用Thor,我想知道,我如何使用Thor分割參數。例如:如何用Ruby和Thor分割參數?

scaffold Post name:string title:string content:text 

我想知道如何name:stringtitle:stringcontent:text分開成「名」和「類型」的對象數組。

回答

-1
"your:string:here".split(":") => ["your", "string", "here"] 
1

考慮你有一個文件scaffold.rb有以下內容:

array = ARGV.map { |column_string| column_string.split(":").first } 
puts array.inspect # or 'p array' 

然後,如果我們運行ruby scaffold.rb name:string title:string content:text,你會得到

["name", "title", "content"] 

如果我們的代碼是p ARGV,然後輸出會是["name:string", "title:string", "content:text"]。因此,我們將得到我們之後所傳遞的任何內容,ruby scaffold.rb作爲在代碼內部由ARGV變量分隔的數組。我們可以根據需要在代碼中操作這個數組。

免責聲明:我不知道雷神,而是想表明這是如何在Ruby中

1

我的建議是使用任何Rails使用這樣你就不會重新發明輪子來完成。我在發生器源代碼中挖了一下,發現rails使用GeneratedAttribute類將參數轉換爲對象。

generator named_base源你會看到他們分裂論據「:」,然後把這些給Rails::Generators::GeneratedAttribute

def parse_attributes! #:nodoc: 
    self.attributes = (attributes || []).map do |key_value| 
    name, type = key_value.split(':') 
    Rails::Generators::GeneratedAttribute.new(name, type) 
    end 
end 

您不必使用GeneratedAttribute類,但它的存在,如果你想要它。