Class: CLI::App

Inherits:
Object
  • Object
show all
Defined in:
lib/cli/app.rb

Overview

An App

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(binary, &block) ⇒ App

Returns a new instance of App.



9
10
11
12
13
14
15
16
17
18
19
# File 'lib/cli/app.rb', line 9

def initialize(binary, &block)
  @binary = binary
  @name = binary
  @actions = {}
  @use_actions = false
  @proxy = Proxy.new(self)
  @args = []
  @opts = OptionParser.new
  @options = {}
  proxy.instance_eval &block
end

Instance Attribute Details

#argsObject (readonly)

Returns the value of attribute args.



7
8
9
# File 'lib/cli/app.rb', line 7

def args
  @args
end

#binaryObject

Returns the value of attribute binary.



6
7
8
# File 'lib/cli/app.rb', line 6

def binary
  @binary
end

#nameObject

Returns the value of attribute name.



6
7
8
# File 'lib/cli/app.rb', line 6

def name
  @name
end

#optionsObject (readonly)

Returns the value of attribute options.



7
8
9
# File 'lib/cli/app.rb', line 7

def options
  @options
end

#optsObject (readonly)

Returns the value of attribute opts.



7
8
9
# File 'lib/cli/app.rb', line 7

def opts
  @opts
end

#proxyObject (readonly)

Returns the value of attribute proxy.



7
8
9
# File 'lib/cli/app.rb', line 7

def proxy
  @proxy
end

#versionObject

Returns the value of attribute version.



6
7
8
# File 'lib/cli/app.rb', line 6

def version
  @version
end

Instance Method Details

#action(name, &block) ⇒ Object

Defines an action



27
28
29
30
31
# File 'lib/cli/app.rb', line 27

def action(name, &block)
  @use_actions = true if name != "default"

  @actions[name] = block
end

#actionsObject

Hash of action_name => block to be executed



22
23
24
# File 'lib/cli/app.rb', line 22

def actions
  @actions
end

#run(action_name) ⇒ Object

Runs an action



34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/cli/app.rb', line 34

def run(action_name)
  block = @actions[action_name]

  unless block
    if action_name == "default"
      raise RuntimeError, "Error: you have to define 'default' action"
    end

    raise ArgumentError, "action '#{action_name}' not found"
  end

  instance_eval &block
end

#run!(args) ⇒ Object

Parses the arguments (with OptionParser) and runs specified or default action.



50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/cli/app.rb', line 50

def run!(args)
  @opts.parse!(args)
  @args = args

  begin
    if args == [] || @use_actions == false
      run "default"
    else
      run args[0]
    end
  rescue => e
    puts e.message.capitalize
  end
end