Skip to content

Commit 98ebfd2

Browse files
authored
Merge pull request #784 from movermeyer/movermeyer/add_enum_validation_to_array_values
Check if `type: array` values are in `enum`
2 parents cb53d45 + b3f2e0a commit 98ebfd2

File tree

2 files changed

+16
-1
lines changed

2 files changed

+16
-1
lines changed

lib/thor/parser/arguments.rb

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,15 @@ def parse_hash(name)
118118
def parse_array(name)
119119
return shift if peek.is_a?(Array)
120120
array = []
121-
array << shift while current_is_value?
121+
while current_is_value?
122+
value = shift
123+
if !value.empty? && @switches.is_a?(Hash) && switch = @switches[name]
124+
if switch.enum && !switch.enum.include?(value)
125+
raise MalformattedArgumentError, "Expected all values of '#{name}' to be one of #{switch.enum.join(', ')}; got #{value}"
126+
end
127+
end
128+
array << value
129+
end
122130
array
123131
end
124132

spec/parser/options_spec.rb

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -509,6 +509,13 @@ def remaining
509509
create attributes: Thor::Option.new("attributes", type: :array, repeatable: true)
510510
expect(parse("--attributes", "1", "2", "--attributes", "3", "4")["attributes"]).to eq([["1", "2"], ["3", "4"]])
511511
end
512+
513+
it "raises error when value isn't in enum" do
514+
enum = %w(apple banana)
515+
create :fruit => Thor::Option.new("fruits", :type => :array, :enum => enum)
516+
expect { parse("--fruits=", "apple", "banana", "strawberry") }.to raise_error(Thor::MalformattedArgumentError,
517+
"Expected all values of '--fruits' to be one of #{enum.join(', ')}; got strawberry")
518+
end
512519
end
513520

514521
describe "with :numeric type" do

0 commit comments

Comments
 (0)