在一个独立的ruby可执行文件中命名命令的空间 [英] Namespacing thor commands in a standalone ruby executable

查看:93
本文介绍了在一个独立的ruby可执行文件中命名命令的空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在命令行上调用thor命令时,方法通过其模块/类结构来命名,例如

When calling thor commands on the command line, the methods are namespaced by their module/class structure, e.g.

class App < Thor
  desc 'hello', 'prints hello'
  def hello
    puts 'hello'
  end
end

将使用命令运行

thor app:hello

但是,如果通过放置使该自我可执行文件

However, if you make that self executable by putting

App.start

在底部,您可以运行以下命令:

at the bottom you can run the command like:

app hello

有什么方法可以对这些命令进行命名空间?这样您就可以拨打电话

Is there any way to namespace those commands? So that you could call, for example

app say:hello
app say:goodbye

推荐答案

另一种方法是使用寄存器:

Another way of doing this is to use register:

class CLI < Thor
  register(SubTask, 'sub', 'sub <command>', 'Description.')
end

class SubTask < Thor
  desc "bar", "..."
  def bar()
    # ...
  end
end

CLI.start

现在-假设您的可执行文件名为foo-您可以调用:

Now - assuming your executable is called foo - you can call:

$ foo sub bar

在当前版本(0.15.0.rc2)中,存在一个错误,该错误会导致帮助文本跳过子命令的命名空间:

In the current thor version (0.15.0.rc2) there is a bug though, which causes the help texts to skip the namespace of sub commands:

$ foo sub
Tasks:
   foo help [COMMAND]  # Describe subcommands or one specific subcommand
   foo bar             #

您可以通过覆盖self.banner并显式设置名称空间来解决此问题.

You can fix that by overriding self.banner and explicitly setting the namespace.

class SubTask < Thor
  namespace :sub

  def bar ...

  def self.banner(task, namespace = true, subcommand = false)
    "#{basename} #{task.formatted_usage(self, true, subcommand)}"
  end
end

formatted_usage的第二个参数是与标语的原始实现的唯一区别.您也可以执行一次此操作,并使其他子命令类从SubTask继承.现在您得到了:

The second parameter of formatted_usage is the only difference to the original implemtation of banner. You can also do this once and have other sub command thor classes inherit from SubTask. Now you get:

$ foo sub
Tasks:
   foo sub help [COMMAND]  # Describe subcommands or one specific subcommand
   foo sub bar             #

希望有帮助.

这篇关于在一个独立的ruby可执行文件中命名命令的空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆