Skip to content

Instantly share code, notes, and snippets.

@zerowidth
Created January 19, 2011 19:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zerowidth/786670 to your computer and use it in GitHub Desktop.
Save zerowidth/786670 to your computer and use it in GitHub Desktop.
hacky test at declarative mode / subcommand support in trollop, totally unfit for consumption!
require "rubygems"
require "trollop"
Trollop::Parser.module_eval do
def self.mode_parse(args=ARGV, &block)
parser = Parser.new(args, &block)
with_standard_exception_handling(parser) { parser.mode_parse args }
end
def modes
@modes ||= {}
end
def mode(name, &block)
modes[name.to_sym] = block
(@stop_words ||= []) << name.to_s
end
def mode_parse(args)
opts = parse(args)
if args.first && mode = modes[args.first.to_sym]
opts[:modes] ||= []
opts[:modes] << args.first.to_sym
args.shift
instance_eval(&mode)
mode_opts = mode_parse(args)
opts[:modes] = opts[:modes] + (mode_opts.delete(:modes) || [])
opts.merge!(mode_opts)
end
return opts
end
end
parser = Trollop::Parser.new do
opt :debug, "debug flag", :type => :string, :default => "defaulted!"
mode :one do
opt :foo
mode :submode do
opt :mumble
end
end
mode :two do
opt :bar
end
end
opts = Trollop::with_standard_exception_handling parser do
raise Trollop::HelpNeeded if ARGV.empty? # show help screen
o = parser.mode_parse ARGV
# puts parser.inspect
o
end
y opts
y ARGV
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment