Skip to content

Commit 3869000

Browse files
kwatchnobu
andauthored
Enhance to support 'Set' object as an enum (#76)
* Enhance to support 'Set' object as an enum * Add test script for '#make_swithc()' --------- Co-authored-by: Nobuyoshi Nakada <[email protected]>
1 parent 7b1362b commit 3869000

File tree

2 files changed

+52
-1
lines changed

2 files changed

+52
-1
lines changed

lib/optparse.rb

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
#
88
# See OptionParser for documentation.
99
#
10+
require 'set' unless defined?(Set)
1011

1112
#--
1213
# == Developer Documentation (not for RDoc output)
@@ -1500,7 +1501,7 @@ def make_switch(opts, block = nil)
15001501
case o
15011502
when Proc, Method
15021503
block = notwice(o, block, 'block')
1503-
when Array, Hash
1504+
when Array, Hash, Set
15041505
if Array === o
15051506
o, v = o.partition {|v,| Completion.completable?(v)}
15061507
values = notwice(v, values, 'values') unless v.empty?

test/optparse/test_switch.rb

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
# frozen_string_literal: false
2+
3+
require 'test/unit'
4+
require 'optparse'
5+
6+
7+
class TestOptionParserSwitch < Test::Unit::TestCase
8+
9+
def setup
10+
@parser = OptionParser.new
11+
end
12+
13+
def assert_invalidarg_error(msg, &block)
14+
exc = assert_raise(OptionParser::InvalidArgument) do
15+
yield
16+
end
17+
assert_equal "invalid argument: #{msg}", exc.message
18+
end
19+
20+
def test_make_switch__enum_array
21+
p = @parser
22+
p.on("--enum=<val>", ["aa", "bb", "cc"])
23+
p.permute(["--enum=bb"], into: (opts={}))
24+
assert_equal({:enum=>"bb"}, opts)
25+
assert_invalidarg_error("--enum=dd") do
26+
p.permute(["--enum=dd"], into: (opts={}))
27+
end
28+
end
29+
30+
def test_make_switch__enum_hash
31+
p = @parser
32+
p.on("--hash=<val>", {"aa"=>"AA", "bb"=>"BB"})
33+
p.permute(["--hash=bb"], into: (opts={}))
34+
assert_equal({:hash=>"BB"}, opts)
35+
assert_invalidarg_error("--hash=dd") do
36+
p.permute(["--hash=dd"], into: (opts={}))
37+
end
38+
end
39+
40+
def test_make_switch__enum_set
41+
p = @parser
42+
p.on("--set=<val>", Set.new(["aa", "bb", "cc"]))
43+
p.permute(["--set=bb"], into: (opts={}))
44+
assert_equal({:set=>"bb"}, opts)
45+
assert_invalidarg_error("--set=dd") do
46+
p.permute(["--set=dd"], into: (opts={}))
47+
end
48+
end
49+
50+
end

0 commit comments

Comments
 (0)