如何在字符串方法选项中接受空格
How to accept whitespace in string method options
我有一个方法接受包含空格的字符串选项:
desc 'events', 'List events'
method_option :since, :desc => 'Show events since', :default => "2 years ago"
def events
# ...
end
但似乎参数在空格上天真地分割所以我得到这个错误:
$ example events --since="1 hour ago"
ERROR: "example events" was called with arguments ["hour", "ago"]
Usage: "example events"
如果我将类型更改为数组,我可以让它接受完整值,但这并不是我想要的。
如有任何建议,我们将不胜感激。
编辑
's answer demonstrated that my error wasn't a Thor issue, and it made me to go back and check my assumptions. I'm using the Thor CLI rather than Thor modules, and in my wrapper script I wasn't handling args correctly。我只需要将 ${@}
括在双引号中,如下所示,现在一切都按预期进行。
#!/usr/bin/env bash
ruby -Ilib ./exe/example "${@}"
谢谢@mrlew :)
我不太了解 thor gem,但这段代码可能会起作用:
class Example < Thor
desc 'events', 'List events'
method_option :since, desc: 'Show events since', default: "2 years ago"
def events
puts "since: " + options[:since]
end
end
几点:
desc
第一个参数必须是调用方法的名称。在你的
例如,它是不同的。
- 您必须使用
options[:key]
来检索参数值。
它在这里工作:
$thor example:events
since: 2 years ago
$ thor example:events --since="long time ago"
since: long time ago
我有一个方法接受包含空格的字符串选项:
desc 'events', 'List events'
method_option :since, :desc => 'Show events since', :default => "2 years ago"
def events
# ...
end
但似乎参数在空格上天真地分割所以我得到这个错误:
$ example events --since="1 hour ago"
ERROR: "example events" was called with arguments ["hour", "ago"]
Usage: "example events"
如果我将类型更改为数组,我可以让它接受完整值,但这并不是我想要的。
如有任何建议,我们将不胜感激。
编辑
${@}
括在双引号中,如下所示,现在一切都按预期进行。
#!/usr/bin/env bash
ruby -Ilib ./exe/example "${@}"
谢谢@mrlew :)
我不太了解 thor gem,但这段代码可能会起作用:
class Example < Thor
desc 'events', 'List events'
method_option :since, desc: 'Show events since', default: "2 years ago"
def events
puts "since: " + options[:since]
end
end
几点:
desc
第一个参数必须是调用方法的名称。在你的 例如,它是不同的。- 您必须使用
options[:key]
来检索参数值。
它在这里工作:
$thor example:events
since: 2 years ago
$ thor example:events --since="long time ago"
since: long time ago