Ruby on rails 我如何使用Ruby和Thor分割参数?
我一直在学习Ruby并在一个自我项目中使用Thor,我想知道,如何使用Thor分割参数。例如:Ruby on rails 我如何使用Ruby和Thor分割参数?,ruby-on-rails,ruby,code-generation,thor,Ruby On Rails,Ruby,Code Generation,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.sp
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使用的任何东西,这样你就不会重新发明轮子了。我在generator源代码中搜索了一下,发现rails正在使用一个类将参数转换为对象 从源代码中,您将看到他们正在拆分“:”上的参数,并将这些参数传递给
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
你不必使用这个类,但是如果你想要它,它就在那里
def parse_attributes! #:nodoc:
self.attributes = (attributes || []).map do |key_value|
name, type = key_value.split(':')
Rails::Generators::GeneratedAttribute.new(name, type)
end
end