Class: Command

Inherits:
Object
  • Object
show all
Defined in:
lib/commands-lite/base.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.command_nameObject



61
62
63
64
65
66
67
68
69
# File 'lib/commands-lite/base.rb', line 61

def self.command_name
  ## note: cut-off leading Yorobot:: for now in class name!!!
  ## note: always remove _ for now too!!!
  ## note: do NOT use @@name!!! - one instance variable per class needed!!
  @name ||= self.name.downcase
                     .sub( /^yorobot::/, '' )   ## todo/fix: make "exclude" list configure-able  why? why not?
                     .gsub( /[_-]/, '' )
  @name
end

.inherited(klass) ⇒ Object



77
78
79
80
81
# File 'lib/commands-lite/base.rb', line 77

def self.inherited( klass )
  # puts  klass.class.name  #=> Class
  ## auto-register commands for now - why? why not?
  Commands.register( klass )
end

.option(key, *args) ⇒ Object



7
8
9
# File 'lib/commands-lite/base.rb', line 7

def self.option( key, *args )
  option_defs[ key ] = args
end

.option_defsObject



3
4
5
# File 'lib/commands-lite/base.rb', line 3

def self.option_defs
  @option_defs ||= {}
end

.run(args = []) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/commands-lite/base.rb', line 37

def self.run( args=[] )
  command      = new

  puts "--> (#{command.name})  #{args.join('ยท')}"

  ## check for options
  command.parse!( args )

  puts "     #{command.options.size} opt(s): #{command.options.pretty_inspect}"
  puts "     #{args.size} arg(s):"
  args.each_with_index do |arg,i|
    puts "            #{[i]} >#{arg}<"
  end


  if args.size > 0
    ## todo/check: check/verify arity of run - why? why not?
    command.call( *args )   ## use run - why? why not?
  else
    command.call
  end
end

Instance Method Details

#nameObject



71
# File 'lib/commands-lite/base.rb', line 71

def name() self.class.command_name; end

#optionsObject



13
14
15
# File 'lib/commands-lite/base.rb', line 13

def options
  @options ||= {}
end

#parse!(args) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/commands-lite/base.rb', line 17

def parse!( args )
  ### todo/check - cache option parser!!!! - why? why not?
  OptionParser.new do |parser|
    ## add default banner - overwrite if needed/to customize
    parser.banner = <<TXT

Usage: #{name} [OPTIONS] ARGUMENTS

TXT

    self.class.option_defs.each do | key, on_args|
      parser.on( *on_args ) do |value|
        options[ key ] = value
      end
    end
  end.parse!( args )
end