2012-02-18 15 views
5

Questa domanda è stata avviata here. Ma è cambiato in modo significativo man mano che ho imparato di più su Thor.Come registrare un Thor :: Group come sottocomando con argomenti

Sto provando a creare un sottocomando Thor :: Group che accetta un argomento. Stranamente, funziona se non ci sono argomenti.

Posso usare un Thor :: Group come sottocomando?

Questo funziona quando si digita: foo counter

foo/bin/foo

module Foo 
    class CLI < Thor 
    register(Counter, 'counter', 'counter', 'Count up from the 1.') 
    end 

    class Counter < Thor::Group 
    desc "Prints 1 2" 

    def one 
     puts 1 
    end 

    def two 
     puts 2 
    end 

    end 

end 

Foo::CLI.start 

Ma questo non funziona quando digito: foo counter 5

module Foo 
    class CLI < Thor 
    register(Counter, 'counter', 'counter <number>', 'Count up from the input.') 
    end 

    class Counter < Thor::Group 
    argument :number, :type => :numeric, :desc => "The number to start counting" 
    desc "Prints 2 numbers based on input" 

    def one 
     puts number + 0 
    end 

    def two 
     puts number + 1 
    end 

    end 


end 

Foo::CLI.start 

E risponde: counter was called incorrectly. Call as foo counter number

risposta

3

Ho una soluzione. Invece di utilizzare Thor :: Gruppo sto usando Invocazioni

bin/foo appare così:

#!/usr/bin/env ruby 

require 'foo' 

Foo::CLI.start 

lib/cli.rb - registri 'generano' come un'attività secondaria di del comando di base, pippo :

module Foo 
    class CLI < Thor 
    register(Generate, 'generate', 'generate [something]', 'Type foo generate for more help.') 
    end 
end 

lib/generate.rb appare così:

module Foo 

    class Generate < Thor 

    desc "project [name]", "Prints the project making step" 
    def project(name) 
     puts "making first project file #{name}" 
     invoke :config 
     invoke :project_sub 
    end 

    desc "config [name]", "Prints the config making step" 
    def config(name) 
     puts "making first config file #{name}" 
     invoke :project_sub 
    end 

    desc "project_sub [name]", "Prints the project_sub making step" 
    def project_sub(name) 
     puts "making subsystem file #{name}" 
    end 

    def self.banner(task, namespace = false, subcommand = true) 
     task.formatted_usage(self, true, subcommand).split(':').join(' ') 
    end 

    end 

end 

ora posso scrivere: foo generate project fred

e il risultato sarà:

> making first project file fred 
> making first config file fred 
> making subsystem file fred 

Avviso l'override banner. Vuol dire che digitando: foo generate project con args non validi o mancanti darà il messaggio di aiuto corretta:

"project" was called incorrectly. Call as "foo generate project [name]". 

al contrario di

"project" was called incorrectly. Call as "foo project [name]". 
Problemi correlati