Class: OptimusPrime::Optor

Inherits:
Object show all
Defined in:
lib/optimus_prime/optor.rb

Instance Method Summary collapse

Constructor Details

#initialize(klass, args) ⇒ Optor

Returns a new instance of Optor.



3
4
5
# File 'lib/optimus_prime/optor.rb', line 3

def initialize(klass, args)
  @klass, @args = klass, args
end

Instance Method Details

#command(name, handler) ⇒ Object



19
20
21
# File 'lib/optimus_prime/optor.rb', line 19

def command(name, handler)
  commands[name.to_s] = handler && Command.new(handler, caller)
end

#commandsObject



15
16
17
# File 'lib/optimus_prime/optor.rb', line 15

def commands
  @commands ||= {}
end

#flag(name) ⇒ Object



27
28
29
30
# File 'lib/optimus_prime/optor.rb', line 27

def flag(name)
  @option_list ||= []
  @option_list << name.to_s
end

#help(name) ⇒ Object



23
24
25
# File 'lib/optimus_prime/optor.rb', line 23

def help(name)
  commands[name].help
end

#init(instance) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/optimus_prime/optor.rb', line 42

def init(instance)
  options.each do |key,val|
    instance.instance_variable_set("@#{key}", val)
  end

  Array(@prompt_list).each do |key, prompt|
    next if options[key]
    $stdout.print prompt + ' '
    options[key] = $stdin.gets.chomp
    instance.instance_variable_set("@#{key}", options[key])
  end

  args = @args.dup
  args.each do |val|
    args.delete(val)
    run_command(instance, val, args)
  end
end

#option(name, options = {}) ⇒ Object



32
33
34
35
36
37
38
39
40
# File 'lib/optimus_prime/optor.rb', line 32

def option(name, options={})
  @option_list ||= []
  @option_list << name.to_s + ':'

  if options[:prompt]
    @prompt_list ||= {}
    @prompt_list[name.to_s] = options[:prompt]
  end
end

#optionsObject



7
8
9
10
11
12
13
# File 'lib/optimus_prime/optor.rb', line 7

def options
  @options ||= begin
    list = [''] # need single options for getopts. psh.
    list += @option_list || []
    OptionParser.getopts(@args, *list)
  end
end