Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Check if type: array values are in enum #784

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion lib/thor/parser/arguments.rb
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,15 @@ def parse_hash(name)
def parse_array(name)
return shift if peek.is_a?(Array)
array = []
array << shift while current_is_value?
while current_is_value?
value = shift
if !value.empty? && @switches.is_a?(Hash) && switch = @switches[name]
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we restructure this conditional a bit? The = towards the end is kind of like a shark in calm waters, it's really unexpected.

if switch.enum && !switch.enum.include?(value)
raise MalformattedArgumentError, "Expected all values of '#{name}' to be one of #{switch.enum.join(', ')}; got #{value}"
end
end
array << value
end
array
end

Expand Down
7 changes: 7 additions & 0 deletions spec/parser/options_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -443,6 +443,13 @@ def remaining
create :attributes => Thor::Option.new("attributes", :type => :array, :repeatable => true)
expect(parse("--attributes", "1", "2", "--attributes", "3", "4")["attributes"]).to eq([["1", "2"], ["3", "4"]])
end

it "raises error when value isn't in enum" do
enum = %w(apple banana)
create :fruit => Thor::Option.new("fruits", :type => :array, :enum => enum)
expect { parse("--fruits=", "apple", "banana", "strawberry") }.to raise_error(Thor::MalformattedArgumentError,
"Expected all values of '--fruits' to be one of #{enum.join(', ')}; got strawberry")
end
end

describe "with :numeric type" do
Expand Down