Console Command
Console::Command provides a clean and easy way to create a command line interface for your program. The unique technique utlizes a Commandline to Object Mapping (COM) to make it quick and easy.
Synopsis
Let’s make an executable called ‘mycmd’.
#!/usr/bin/env ruby require 'facet/console_command' MyCmd << Console::Command def _v $VERBOSE = true end def jump if $VERBOSE puts "JUMP! JUMP! JUMP!" else puts "Jump" end end end MyCmd.execute
Then on the command line:
> mycmd jump Jump > mycmd -v jump JUMP! JUMP! JUMP!
Methods
Public Class methods
Starts the command execution.
[ show source ]
# File lib/facets/more/command.rb, line 113 def execute( *args ) new.execute( *args ) end
Do not let this pass through on to any included module.
[ show source ]
# File lib/facets/more/command.rb, line 125 def initialize ; end
Public Instance methods
Execute the command.
[ show source ]
# File lib/facets/more/command.rb, line 129 def execute( *argv ) argv = argv.empty? ? ARGV : argv # process options argv2 = argv.collect { |arg| if md = %r{^-(\w+)}.match( arg ) if md[1].size > 1 md[1].split(//).collect { |c| "-#{c}" } else arg end else arg end }.flatten args = argv2.dup i = 0; while i < args.size if md = %r{^[-]}.match( args[i] ) opt = args[i].gsub('-','_') if self.respond_to?( opt ) m = method( opt ) c = m.arity if c > 0 m.call(*args[i+1..i+c]) args[i..i+c] = nil i += c else m.call args[i] = nil end else $stderr << "Unknown option '#{args[i]}'\n" exit -1 end end i += 1 end args.compact! # no secondary commands if self.respond_to?(:main) main( *args ) # secondary commands elsif not args.empty? if self.respond_to?( args.first ) __send__( *args ) else if self.private_methods.include?( "no_command_error" ) no_command_error( *args ) else $stderr << "Non-applicable command #{args.join(' ')}\n" exit -1 end end # default secondary command elsif self.respond_to?( :default ) default(*args) # error else if self.private_methods.include?( "no_action_error" ) no_action_error( *args ) else $stderr << "Nothing to do.\n" exit -1 end end end