Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Check if numeric value is in enum

  • Loading branch information...
commit 0fea66d32c97bae14bdffa1cf44953cdeed38aae 1 parent 3dd0e8f
@markets markets authored
Showing with 23 additions and 1 deletion.
  1. +9 −1 lib/thor/parser/arguments.rb
  2. +14 −0 spec/parser/options_spec.rb
View
10 lib/thor/parser/arguments.rb
@@ -121,6 +121,7 @@ def parse_array(name)
end
# Check if the peek is numeric format and return a Float or Integer.
+ # Check if the peek is included in enum if enum is provided.
# Otherwise raises an error.
#
def parse_numeric(name)
@@ -130,12 +131,19 @@ def parse_numeric(name)
fail MalformattedArgumentError, "Expected numeric value for '#{name}'; got #{peek.inspect}"
end
- $&.index('.') ? shift.to_f : shift.to_i
+ value = $&.index('.') ? shift.to_f : shift.to_i
+ if @switches.is_a?(Hash) && switch = @switches[name]
+ if switch.enum && !switch.enum.include?(value)
+ raise MalformattedArgumentError, "Expected '#{name}' to be one of #{switch.enum.join(', ')}; got #{value}"
+ end
+ end
+ value
end
# Parse string:
# for --string-arg, just return the current value in the pile
# for --no-string-arg, nil
+ # Check if the peek is included in enum if enum is provided. Otherwise raises an error.
#
def parse_string(name)
if no_or_skip?(name)
View
14 spec/parser/options_spec.rb
@@ -288,6 +288,13 @@ def remaining
expect(parse('--foo=bar', '--foo', '12')['foo']).to eq('12')
expect(parse('--foo', '12', '--foo', '13')['foo']).to eq('13')
end
+
+ it "raises error when value isn't in enum" do
+ enum = %w(apple banana)
+ create :fruit => Thor::Option.new('fruit', :type => :string, :enum => enum)
+ expect{ parse('--fruit', 'orange') }.to raise_error(Thor::MalformattedArgumentError,
+ "Expected '--fruit' to be one of #{enum.join(', ')}; got orange")
+ end
end
describe 'with :boolean type' do
@@ -394,6 +401,13 @@ def remaining
expect { parse('-n', 'foo') }.to raise_error(Thor::MalformattedArgumentError,
"Expected numeric value for '-n'; got \"foo\"")
end
+
+ it "raises error when value isn't in enum" do
+ enum = [1, 2]
+ create :limit => Thor::Option.new('limit', :type => :numeric, :enum => enum)
+ expect{ parse('--limit', '3') }.to raise_error(Thor::MalformattedArgumentError,
+ "Expected '--limit' to be one of #{enum.join(', ')}; got 3")
+ end
end
end
Please sign in to comment.
Something went wrong with that request. Please try again.