Skip to content

Commit 23ec5ba

Browse files
committed
Merge pull request #386 from markets/numeric_enum
Check if numeric value is in enum
2 parents 3dd0e8f + 0fea66d commit 23ec5ba

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

lib/thor/parser/arguments.rb

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,7 @@ def parse_array(name)
121121
end
122122

123123
# Check if the peek is numeric format and return a Float or Integer.
124+
# Check if the peek is included in enum if enum is provided.
124125
# Otherwise raises an error.
125126
#
126127
def parse_numeric(name)
@@ -130,12 +131,19 @@ def parse_numeric(name)
130131
fail MalformattedArgumentError, "Expected numeric value for '#{name}'; got #{peek.inspect}"
131132
end
132133

133-
$&.index('.') ? shift.to_f : shift.to_i
134+
value = $&.index('.') ? shift.to_f : shift.to_i
135+
if @switches.is_a?(Hash) && switch = @switches[name]
136+
if switch.enum && !switch.enum.include?(value)
137+
raise MalformattedArgumentError, "Expected '#{name}' to be one of #{switch.enum.join(', ')}; got #{value}"
138+
end
139+
end
140+
value
134141
end
135142

136143
# Parse string:
137144
# for --string-arg, just return the current value in the pile
138145
# for --no-string-arg, nil
146+
# Check if the peek is included in enum if enum is provided. Otherwise raises an error.
139147
#
140148
def parse_string(name)
141149
if no_or_skip?(name)

spec/parser/options_spec.rb

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -288,6 +288,13 @@ def remaining
288288
expect(parse('--foo=bar', '--foo', '12')['foo']).to eq('12')
289289
expect(parse('--foo', '12', '--foo', '13')['foo']).to eq('13')
290290
end
291+
292+
it "raises error when value isn't in enum" do
293+
enum = %w(apple banana)
294+
create :fruit => Thor::Option.new('fruit', :type => :string, :enum => enum)
295+
expect{ parse('--fruit', 'orange') }.to raise_error(Thor::MalformattedArgumentError,
296+
"Expected '--fruit' to be one of #{enum.join(', ')}; got orange")
297+
end
291298
end
292299

293300
describe 'with :boolean type' do
@@ -394,6 +401,13 @@ def remaining
394401
expect { parse('-n', 'foo') }.to raise_error(Thor::MalformattedArgumentError,
395402
"Expected numeric value for '-n'; got \"foo\"")
396403
end
404+
405+
it "raises error when value isn't in enum" do
406+
enum = [1, 2]
407+
create :limit => Thor::Option.new('limit', :type => :numeric, :enum => enum)
408+
expect{ parse('--limit', '3') }.to raise_error(Thor::MalformattedArgumentError,
409+
"Expected '--limit' to be one of #{enum.join(', ')}; got 3")
410+
end
397411
end
398412

399413
end

0 commit comments

Comments
 (0)