[英]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.