How do I create thor::group generators as args of my_command
Asked Answered
L

1

2

In my gem I'd like to have a an executable command with args like so:

foo generate project
foo generate config
foo say_hi

So I made

foo/bin/foo

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

And the Foo file in foo/lib/thor/foo.rb

module Foo 
  class Foo < Thor

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

    end

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

  end
end

And foo/lib/thor/generators/project.rb And foo/lib/thor/generators/config.rb

Where I'd like to specify classes inherited from Thor::Group like katz examples ...

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

So my question is: How do I set things up so that I can call those generators from the executable like:

foo generate config

Am I on the right track even? Ideally, typing foo on its own should give help for say_hi and for all the generators.

Landes answered 18/2, 2012 at 8:8 Comment(1)
looks like Thor#register may help. I'll persevere.Landes
D
7

I had trouble getting this to work at first, too. Here's the pattern that I've started using:

$ 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 greet

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 delete

Deleting a sub-thing
Dumpling answered 23/5, 2012 at 15:8 Comment(1)
This looks good, thanks! And it seems you have no issues getting the help to be properly formatted. I managed to get things working but had to parse the help string to remove colons. I'll use your solution in future.Landes

© 2022 - 2024 — McMap. All rights reserved.