blob: 2d9ad2a1364e4fa72588590074029f474b75bda7 (
plain)
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
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
|
class Slop
class Options < Array
def to_hash
each_with_object({}) do |option, out|
out[option.key] = option.argument_value
end
end
def [](item)
item = item.to_s
if item =~ /^\d+$/
slice(item.to_i)
else
find do |option|
option.short_flag == item || option.long_flag == item
end
end
end
end
class Option
attr_reader :short_flag
attr_reader :long_flag
attr_reader :description
attr_reader :callback
attr_writer :argument_value
def initialize(slop, short, long, description, argument, options={}, &blk)
@slop = slop
@short_flag = short
@long_flag = long
@description = description
@expects_argument = argument
@options = options
if @long_flag && @long_flag.size > @slop.longest_flag
@slop.longest_flag = @long_flag.size
end
@callback = blk if block_given?
@callback ||= options[:callback]
@argument_value = nil
end
def expects_argument?
@expects_argument || @options[:argument]
end
def accepts_optional_argument?
@options[:optional]
end
def key
@long_flag || @short_flag
end
def default
@options[:default]
end
def argument_value
value = @argument_value || default
return if value.nil?
case @options[:as].to_s
when 'Array'
value.split(@options[:delimiter] || ',', @options[:limit] || 0)
when 'String'; value.to_s
when 'Symbol'; value.to_s.to_sym
when 'Integer'; value.to_s.to_i
when 'Float'; value.to_s.to_f
else
value
end
end
def to_s
out = " "
out += @short_flag ? "-#{@short_flag}, " : ' ' * 4
if @long_flag
out += "--#{@long_flag}"
diff = @slop.longest_flag - @long_flag.size
spaces = " " * (diff + 6)
out += spaces
else
spaces = " " * (@slop.longest_flag + 8)
out += spaces
end
"#{out}#{@description}"
end
def inspect
"#<Slop::Option short_flag=#{@short_flag.inspect} " +
"long_flag=#{@long_flag.inspect} " +
"description=#{@description.inspect}>"
end
end
end
|