【问题标题】:How can I pass a switch before the command in a Thor app?如何在 Thor 应用程序中的命令之前传递一个开关?
【发布时间】:2019-02-21 00:38:06
【问题描述】:

我有一个 Thor 应用程序,它的所有命令都需要许多相同的参数。通用参数用class_option 声明。但我希望用户将这些放在命令之前。

例如,我的用户可能需要键入此序列...

mycli cmd1 arg1 arg2 --switch1 --switch2=value
mycli cmd2 arg3 arg4 --switch1 --switch2=value
mycli cmd3 arg5 arg6 --switch1 --switch2=value

每次我的用户需要重新键入或显着退格来编辑命令行时。这样做会更容易......

mycli --switch1 --switch2=value cmd1 arg1 arg2
mycli --switch1 --switch2=value cmd2 arg3 arg4
mycli --switch1 --switch2=value cmd3 arg5 arg6

这样,每次调用需要更改的部分在命令行的末尾,而可能保持不变的参数在开头。命令行编辑变得非常简单。

在 Thor 中是否有任何方法支持这一点?

【问题讨论】:

  • 它没有回答你的问题,但你可以做ctrl+a meta+f,即转到行首,前进一个单词。作为额外的奖励,删除 cmds 和 args 只是 ctrl+d ctrl+d ctrl+d

标签: ruby thor


【解决方案1】:

简要查看文档和示例以及标准 ruby​​ 约定将表明选项应该最后传递。但这里是你如何使用 ruby​​ 脚本来“排序”你的命令行,这是一个基本的例子:

#test.thor

class Test < Thor
  method_option :demo, :aliases => "-d", :desc => "demo"
  method_option :foo, :aliases => "-f", :desc => "foo"
  method_option :bar, :aliases => "-b", :desc => "bar"
  desc "example", "an example task"
  def example
    puts "option switches passed: #{options.to_s}"
  end
end

还有你的 ruby​​ 脚本,你可以制作 exec、别名等:

#hack.rb

#!/usr/bin/env ruby
args = ARGV
cmd = args.reject{|a| a[0] == '-'}.first
switches = args.select{|a| a[0] == '-'}
cmd_args = args[1..-1] - switches
system_cmd = ['thor', cmd, args, switches].join(' ')
system(system_cmd)

为了测试目的,您可以像这样调用它:

thor test:example -f -d -b
#=>option switches passed: {"foo"=>"foo", "demo"=>"demo", "bar"=>"bar"}

ruby hack.rb -f -b -d test:example
#=> option switches passed: {"foo"=>"foo", "bar"=>"bar", "demo"=>"demo"}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-01
    • 2012-02-26
    • 2014-09-07
    • 2015-06-08
    • 2015-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多