如何使用或添加子命令功能与托尔?

时间:2011-06-17 12:00:01

标签: ruby rubygems thor

我正在使用thor创建一个CLI应用程序。它进展顺利,但现在我坚持使用子命令功能。

github wiki中没有任何内容可以搜索,但没有任何帮助。

那么,有人可以展示或指出如何实现子命令功能吗?

2 个答案:

答案 0 :(得分:3)

退房:http://whatisthor.com/

从该站点(编辑一点以节省空间并突出显示子命令用法):

module GitCLI
  class Remote  ", "Adds a remote named  for the repository at "
    option :t, :banner => ""
    option :m, :banner => ""
    options :f => :boolean, :tags => :boolean, :mirror => :string
    def add(name, url)
      # implement git remote add
    end

    desc "rename  ", "Rename the remote named  to "
    def rename(old, new)
    end
  end

  class Git  [...]", "Download objects and refs from another repository"
    options :all => :boolean, :multiple => :boolean
    option :append, :type => :boolean, :aliases => :a
    def fetch(respository, *refspec)
      # implement git fetch here
    end

    desc "remote SUBCOMMAND ...ARGS", "manage set of tracked repositories"
    subcommand "remote", Remote  ### SUBCOMMAND USED HERE...
  end
end

... h个

答案 1 :(得分:1)

尝试这样的事情(文件test.rb):

#!/usr/bin/env ruby

require 'rubygems'
require 'thor'
require 'thor/group'  # This is required -- it's not a bug, it's a feature!

class Bar < Thor
  desc "baz", "Whatever"
  def baz
    puts "Hello from Bar"
  end
end

class Foo < Thor
  desc "go", "Do something"
  def go
    puts "Hello there!"
  end

  register Bar, :bar, "bar", "Do something else"
end

if __FILE__ == $0
  Foo.start
end

表现如下:

> test.rb
Tasks:
  test.rb bar          # Do something else
  test.rb go           # Do something
  test.rb help [TASK]  # Describe available tasks or one specific task

> test.rb go
Hello there!
> test.rb bar
Tasks:
  test.rb baz             # Whatever
  test.rb help [COMMAND]  # Describe subcommands or one specific subcommand

> test.rb bar baz
Hello from Bar
> test.rb baz
Could not find task "baz".
>

(这大部分按预期工作,除了“test.rb bar”的帮助信息不太正确,恕我直言。我认为它应该说“test.rb bar baz ...”,而不是“test。 rb baz ......“。)

希望这有帮助!