我如何创建thor::group生成器作为my_command的args?[英] How do I create thor::group generators as args of my_command

本文是小编为大家收集整理的关于我如何创建thor::group生成器作为my_command的args?的处理方法,想解了我如何创建thor::group生成器作为my_command的args?的问题怎么解决?我如何创建thor::group生成器作为my_command的args?问题的解决办法?那么可以参考本文帮助大家快速定位并解决问题。

问题描述

在我的 gem 中,我想要一个带有 args 的可执行命令,如下所示:

foo generate project
foo generate config
foo say_hi

所以我做了

foo/bin/foo

#!/usr/bin/env ruby
require 'foo'
Foo::Foo.start

还有foo/lib/thor/foo.rb中的Foo文件

module Foo 
  class Foo < Thor

    desc "generate [WHAT]"
    def generate(*args)

    end

    desc "say_hi"
    def say_hi(*args)
       ....
    end

  end
end

还有 foo/lib/thor/generators/project.rb还有 foo/lib/thor/generators/config.rb

我想指定继承自 Thor::Group 的类,例如 katz 示例...

module Foo
  module Generators
    class Project < Thor::Group
      include Thor::Actions
      ....
    end
  end
end

所以我的问题是:如何设置以便我可以从可执行文件中调用这些生成器,例如:

foo generate config

我在正确的轨道上吗?理想情况下,单独键入 foo 应该为 say_hi 和所有生成器提供帮助.

推荐答案

一开始我也遇到了麻烦.这是我开始使用的模式:

$ cat cli.rb

#!/usr/bin/env ruby
require 'rubygems'
require 'thor'
require 'thor/group'

module CLI
  class Greeter < Thor::Group
    def say_hi
      say "Hi"
    end
    def say_goodbye
      say "Goodbye"
    end
  end
end

module CLI
  class Crud < Thor
    desc 'create', 'Creates a sub-thing'
    def create
      say "Creating a sub-thing"
    end

    desc 'delete', 'Deletes a sub-thing'
    def delete
      say "Deleting a sub-thing"
    end

  end
end

module CLI
  class Root < Thor
    register CLI::Greeter, 'greet', 'greet', 'Executes a multi-step subtask'
    register CLI::Crud, 'crud', 'crud [COMMAND]', 'Delegates to a sub-command'
  end
end

CLI::Root.start

$ ./cli.rb

Tasks:
  cli.rb crud [COMMAND]  # Delegates to a sub-command
  cli.rb greet           # Executes a multi-step subtask
  cli.rb help [TASK]     # Describe available tasks or one specific task

$ ./cli.rb 问候

Hi
Goodbye

$ ./cli.rb crud

Tasks:
  cli.rb crud create          # Creates a sub-thing
  cli.rb crud delete          # Deletes a sub-thing
  cli.rb crud help [COMMAND]  # Describe subcommands or one specific subcommand

$ ./cli.rb crud create

Creating a sub-thing

$ ./cli.rb crud 删除

Deleting a sub-thing

本文地址:https://www.itbaoku.cn/post/786569.html