Skip to content

Instantly share code, notes, and snippets.

Revisions

  1. @sss sss created this gist Feb 24, 2012.
    19 changes: 19 additions & 0 deletions executable-with-subcommands-using-thor.log
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,19 @@
    $ ./executable-with-subcommands-using-thor.rb
    Tasks:
    executable-with-subcommands-using-thor.rb help [TASK] # Describe available tasks or one specific task
    executable-with-subcommands-using-thor.rb subA [TASK] # Execute a task in namespace subA
    executable-with-subcommands-using-thor.rb subB [TASK] # Execute a task in namespace subB
    executable-with-subcommands-using-thor.rb test # test in CLI

    $ ./executable-with-subcommands-using-thor.rb help
    Tasks:
    executable-with-subcommands-using-thor.rb help [TASK] # Describe available tasks or one specific task
    executable-with-subcommands-using-thor.rb subA [TASK] # Execute a task in namespace subA
    executable-with-subcommands-using-thor.rb subB [TASK] # Execute a task in namespace subB
    executable-with-subcommands-using-thor.rb test # test in CLI

    $ ./executable-with-subcommands-using-thor.rb subA help test
    Usage:
    executable-with-subcommands-using-thor.rb subA test

    test in SubCommandA
    58 changes: 58 additions & 0 deletions executable-with-subcommands-using-thor.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,58 @@
    #!/usr/bin/env ruby
    # -*- encoding: UTF-8 -*-

    # Derived from <http://stackoverflow.com/questions/5663519/namespacing-thor-commands-in-a-standalone-ruby-executable>

    require 'rubygems'
    require 'thor'
    require 'thor/group'

    module MyApp
    class ThorSubCommandTemplate < Thor
    class << self
    def subcommand_setup(name, usage, desc)
    namespace :"#{name}"
    @subcommand_usage = usage
    @subcommand_desc = desc
    end

    def banner(task, namespace = nil, subcommand = false)
    "#{basename} #{task.formatted_usage(self, true, true)}"
    end

    def register_to(klass)
    klass.register(self, @namespace, @subcommand_usage, @subcommand_desc)
    end
    end
    end

    class SubCommandA < ThorSubCommandTemplate
    subcommand_setup "subA", "subA [TASK]", "Execute a task in namespace subA"

    desc "test", "test in SubCommandA"
    def test
    # ...
    end
    end

    class SubCommandB < ThorSubCommandTemplate
    subcommand_setup "subB", "subB [TASK]", "Execute a task in namespace subB"

    desc "test", "test in SubCommandB"
    def test
    # ...
    end
    end

    class CLI < Thor
    SubCommandA.register_to(self)
    SubCommandB.register_to(self)

    desc "test", "test in CLI"
    def test
    # ...
    end
    end
    end

    MyApp::CLI.start