[英]How do I split arguments with Ruby and Thor?
我一直在學習Ruby,並在一個自我項目中使用Thor,所以我想知道如何使用Thor分割參數。 例如:
scaffold Post name:string title:string content:text
我想知道如何將name:string
, title:string
和content:text
拆分為具有“ name”和“ type”的對象數組。
考慮您具有以下內容的文件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
變量中按空格分割的數組。 我們可以在代碼內部按需操作此數組。
免責聲明:我不了解Thor,但想展示如何在Ruby中完成此操作
我的建議是使用Rails所使用的任何東西,這樣您就不會重新發明輪子了。 我在生成器源代碼中進行了一些挖掘,發現rails正在使用GeneratedAttribute類將參數轉換為對象。
從生成器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類,但是如果需要它就可以使用。
"your:string:here".split(":") => ["your", "string", "here"]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.