Skip to content

Commit

Permalink
Change keywords parsing to collect or raised on unrecognized parameters
Browse files Browse the repository at this point in the history
  • Loading branch information
piotrmurach committed Apr 30, 2020
1 parent 9081d43 commit a5c1fab
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
5 changes: 5 additions & 0 deletions lib/tty/option/parser/keywords.rb
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ class Keywords
# @api public
def initialize(keywords, **config)
@keywords = keywords
@check_invalid_params = config.fetch(:check_invalid_params) { true }
@error_aggregator = ErrorAggregator.new(**config)
@required_check = RequiredCheck.new(@error_aggregator)
@arity_check = ArityCheck.new(@error_aggregator)
Expand Down Expand Up @@ -100,6 +101,10 @@ def next_keyword
else
value = val
end
elsif @check_invalid_params
@error_aggregator.(InvalidParameter, "invalid keyword #{match}")
else
@remaining << match.to_s
end
end

Expand Down
21 changes: 21 additions & 0 deletions spec/unit/parser/keywords_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,27 @@ def parse(argv, kwargs, **config)
expect(errors[:bar]).to eq({missing_parameter: "need to provide 'bar' keyword"})
end

it "parses unrecognized keywords and collects error" do
keywords = []
keywords << keyword(:foo)
params, rest, errors = parse(%w[foo=a unknown=b], keywords,
raise_on_parsing_error: false)

expect(params[:foo]).to eq("a")
expect(rest).to eq([])
expect(errors[:messages]).to eq([{invalid_parameter: "invalid keyword unknown=b"}])
end

it "parses unrecognized keywords and doesn't check invalid parameter" do
keywords = []
keywords << keyword(:foo)
params, rest, errors = parse(%w[foo=a unknown=b], keywords,
check_invalid_params: false)
expect(params[:foo]).to eq("a")
expect(rest).to eq(["unknown=b"])
expect(errors).to eq({})
end

context "when multiple times" do
it "parses last keyword without arity" do
params, rest = parse(%w[foo=1 foo=2], keyword(:foo))
Expand Down

0 comments on commit a5c1fab

Please sign in to comment.