2

我一直在学习 Ruby 并在自己的项目中使用 Thor,我想知道如何使用 Thor 拆分参数。例如:

scaffold Post name:string title:string content:text

我想知道如何将 , 拆分name:string成一个带有“名称”和“类型”的对象数组title:stringcontent:text

4

3 回答 3

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我们可以在代码中随意操作这个数组。

免责声明:我不认识 Thor,但想展示一下这是如何在 Ruby 中完成的

于 2011-12-12T12:51:37.527 回答
1

我的建议是使用 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类,但如果需要,它就在那里。

于 2011-12-12T12:59:23.107 回答
-1
"your:string:here".split(":") => ["your", "string", "here"]
于 2011-12-12T11:17:44.453 回答