Class: PostageApp::CLI::Command
- Inherits:
-
Object
- Object
- PostageApp::CLI::Command
show all
- Defined in:
- lib/postageapp/cli/command.rb
Defined Under Namespace
Classes: APICallError, MissingArguments
Class Method Summary
collapse
Instance Method Summary
collapse
Constructor Details
#initialize(command_name) ⇒ Command
Returns a new instance of Command.
21
22
23
24
25
|
# File 'lib/postageapp/cli/command.rb', line 21
def initialize(command_name)
@command_name = command_name
@api_key_context = :project
@argument = { }
end
|
Class Method Details
.define(command_name = nil, &block) ⇒ Object
14
15
16
17
18
19
|
# File 'lib/postageapp/cli/command.rb', line 14
def self.define(command_name = nil, &block)
command_name ||= $command_name
command = self.defined[command_name] = new(command_name)
command.instance_eval(&block) if (block_given?)
end
|
.defined ⇒ Object
10
11
12
|
# File 'lib/postageapp/cli/command.rb', line 10
def self.defined
@defined ||= { }
end
|
Instance Method Details
#api_key(context) ⇒ Object
27
28
29
|
# File 'lib/postageapp/cli/command.rb', line 27
def api_key(context)
@api_key_context = context
end
|
#argument(name, optional: false, type: String, desc: nil, boolean: false) ⇒ Object
31
32
33
34
35
36
37
38
|
# File 'lib/postageapp/cli/command.rb', line 31
def argument(name, optional: false, type: String, desc: nil, boolean: false)
@argument[name] = {
optional: optional,
type: String,
desc: desc,
boolean: boolean
}
end
|
#parse!(*args) ⇒ Object
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
|
# File 'lib/postageapp/cli/command.rb', line 44
def parse!(*args)
arguments = { }
op = OptionParser.new do |parser|
parser.banner = "Usage: postageapp #{@command_name} [options]"
@argument.each do |name, attributes|
if (attributes[:boolean])
parser.on("--#{name}", attributes[:desc]) do
arguments[name] = true
end
else
parser.on("--#{name} VALUE", "#{attributes[:desc]} (#{attributes[:optional] ? 'optional' : 'required'})") do |v|
arguments[name] = v
end
end
end
end
op.parse!(args)
missing = @argument.select do |name, attributes|
!attributes[:optional] && arguments[name].nil?
end.keys
if (missing.any?)
$stderr.puts("Error: missing options #{missing.join(', ')}")
puts op.help
raise MissingArguments
end
case (@api_key_context)
when :account
arguments['api_key'] = PostageApp.configuration.account_api_key
end
case (@perform&.arity)
when 1
return @perform.call(arguments)
when 0
return @perform.call
end
response = PostageApp::Request.new(@command_name, arguments).send
case (response.status)
when "ok"
puts JSON.pretty_generate(response.data)
else
$stderr.puts("Received error: #{response.status}")
if (response.message)
$stderr.puts(' ' + response.message)
end
raise APICallError
end
end
|
40
41
42
|
# File 'lib/postageapp/cli/command.rb', line 40
def perform(&block)
@perform = block
end
|