Skip to content

Instantly share code, notes, and snippets.

@sss
Created February 24, 2012 20:16
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sss/1903461 to your computer and use it in GitHub Desktop.
Save sss/1903461 to your computer and use it in GitHub Desktop.
Revised: Namespacing thor commands in a standalone Ruby executable
$ ./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
#!/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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment