12

thor wiki 页面Making an Exectable向您展示了如何创建一个由 thor 驱动的 CLI 命令,如下所示:

bash ./mythorcommand foo

这要求您将 thor 任务foo作为第一个参数传入。

我还可以使用 thor 的default_method运行不带任何参数的 thor 可执行文件:

bash ./mythorcommand

但是,我想传入一个变量字符串作为第一个参数:

bash ./mythorcommand "somevalue"

这不起作用,因为 thor 命令期望第一个参数是任务名称。有没有办法忽略任务名称并将第一个参数发送到默认方法?

如果此功能不存在,我认为添加一种将所有命令行参数传递给一个任务/方法的方法将非常有用:

class MyThorCommand < Thor
  only_method :default

  def default(*args)
    puts args.inpsect
  end 
end 

MyThorCommand.start
4

3 回答 3

4

您应该从 Thor::Group 和调用 start 方法扩展

class Test < Thor::Group
  desc "Act description"
  def act
    puts "do smth"
  end
end

Test.start
于 2011-12-02T20:34:47.743 回答
3

我为这个问题找到了一个相当“奇怪”的解决方案,对我来说效果很好。

您将默认任务添加到 Thor。然后添加 method_missing 以便在应用程序有参数时欺骗 Thor 将默认方法作为参数传递。

以您的示例为例,解决方案如下所示:

class MyThorCommand < Thor
  default_task :my_default

  desc "my_default", "A simple default"
  def my_default(*args)
    puts args.inspect
  end 

  def method_missing(method, *args)
    args = ["my_default", method.to_s] + args
    MyThorCommand.start(args)
  end

end 

MyThorCommand.start(ARGV)

如果这是在文件“my_thor.rb”中,则执行“ruby my_thor.rb foo bar”将显示“[“foo”,“bar”]'作为结果。

希望能帮助到你。

于 2014-05-30T13:38:28.810 回答
1

尽管这并不能完全解决您的问题,但一种替代方法可能是Thor.map通过仅提供选项标志来调用命令:

map '-F' => 'foo'

现在也可以传参数了

mythorcommand -F bar # => invokes foo("bar")
于 2011-09-05T17:57:08.417 回答