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
[ show source ]
# File lib/facets/more/consoleapp.rb, line 85 def self.execute( *args ) new.execute( *args ) end
[ show source ]
# File lib/facets/more/consoleapp.rb, line 89 def initialize # do not let this pass through on to # any included module. end
Public Instance methods
This method is also aliased as
go
[ show source ]
# File lib/facets/more/consoleapp.rb, line 94 def execute( argv=nil ) argv ||= ARGV # argv remains unchanged args = argv.dup # args is manipulated # process options i = 0; while i < argv.size if md = %r{^[-]}.match( argv[i] ) opt = argv[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 #{ARGV[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
Alias for execute