命名空间Thor命令在独立的ruby可执行文件中

phi*_*ash 16 ruby thor

在命令行上调用thor命令时,这些方法按其模块/类结构命名,例如

class App < Thor
  desc 'hello', 'prints hello'
  def hello
    puts 'hello'
  end
end
Run Code Online (Sandbox Code Playgroud)

将使用该命令运行

thor app:hello
Run Code Online (Sandbox Code Playgroud)

但是,如果你通过推杆使自己可执行

App.start
Run Code Online (Sandbox Code Playgroud)

在底部你可以运行如下命令:

app hello
Run Code Online (Sandbox Code Playgroud)

有没有办法命名这些命令?例如,你可以打电话

app say:hello
app say:goodbye
Run Code Online (Sandbox Code Playgroud)

tfi*_*ach 24

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

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

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

CLI.start
Run Code Online (Sandbox Code Playgroud)

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

$ foo sub bar
Run Code Online (Sandbox Code Playgroud)

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

$ foo sub
Tasks:
   foo help [COMMAND]  # Describe subcommands or one specific subcommand
   foo bar             #
Run Code Online (Sandbox Code Playgroud)

您可以通过重写self.banner并显式设置命名空间来解决此问题.

class SubTask < Thor
  namespace :sub

  def bar ...

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

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

$ foo sub
Tasks:
   foo sub help [COMMAND]  # Describe subcommands or one specific subcommand
   foo sub bar             #
Run Code Online (Sandbox Code Playgroud)

希望有所帮助.


Ian*_*ton 5

这是App作为默认命名空间的一种方式(虽然非常hacky):

#!/usr/bin/env ruby
require "rubygems"
require "thor"

class Say < Thor
  # ./app say:hello
  desc 'hello', 'prints hello'
  def hello
    puts 'hello'
  end
end

class App < Thor
  # ./app nothing
  desc 'nothing', 'does nothing'
  def nothing
    puts 'doing nothing'
  end
end

begin
  parts = ARGV[0].split(':')
  namespace = Kernel.const_get(parts[0].capitalize)
  parts.shift
  ARGV[0] = parts.join
  namespace.start
rescue
  App.start
end
Run Code Online (Sandbox Code Playgroud)

或者,也不理想:

define_method 'say:hello'
Run Code Online (Sandbox Code Playgroud)