-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathwboptionsparser.rb
56 lines (47 loc) · 1.1 KB
/
wboptionsparser.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
require "optparse"
require "ostruct"
# Creates a default command-line argument parser.
# command_name: For help text.
def create_parser(command_name)
OptionParser.new do |parser|
parser.banner = "Usage: ./project.rb #{command_name} [options]"
parser
end
end
class WbOptionsParser
# Allows parsing of command line options without requiring any subclassing.
attr_reader :opts, :remaining
def initialize(command_name, args)
@opts = OpenStruct.new
@parser = create_parser(command_name)
@args = args
@validators = []
end
def add_option(option, assign, help)
@parser.on(option, help) {|v| assign.call(@opts, v)}
self
end
def add_typed_option(option, type, assign, help)
@parser.on(option, type, help) {|v| assign.call(@opts, v)}
self
end
def add_validator(fn)
@validators.push(fn)
self
end
def parse()
@remaining = @parser.parse @args
self
end
def validate()
@validators.each do |fn|
begin
fn.call(@opts)
rescue ArgumentError
STDERR.puts @parser.help
exit 1
end
end
self
end
end