Skip to content

Commit

Permalink
Support for required options
Browse files Browse the repository at this point in the history
This commit introduces support for required options,
which are options that cause the parser to raise
a `MissingRequiredOption` exception if not present.

Options can be marked as required by passing
`required: true` in their configuration, and any errors
caused by missing required options can be suppressed via
`suppress_errors: true`.
  • Loading branch information
woodruffw committed Sep 29, 2017
1 parent ec47929 commit 2e3f3d0
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 0 deletions.
5 changes: 5 additions & 0 deletions lib/slop/error.rb
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,9 @@ def initialize(msg, flag)
@flag = flag
end
end

# Raised when a required option is *not* parsed.
# Suppress with the `suppress_errors` config option.
class MissingRequiredOption < Error
end
end
1 change: 1 addition & 0 deletions lib/slop/option.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ class Option
help: true,
tail: false,
underscore_flags: true,
required: false,
}

# An Array of flags this option matches.
Expand Down
7 changes: 7 additions & 0 deletions lib/slop/parser.rb
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,13 @@ def parse(strings)

@arguments += ignored_args

unused_options.each do |o|
if o.config[:required] && !suppress_errors?
pretty_flags = o.flags.map { |f| "`#{f}'" }.join(", ")
raise MissingRequiredOption, "missing required option #{pretty_flags}"
end
end

Result.new(self).tap do |result|
used_options.each { |o| o.finish(result) }
end
Expand Down
14 changes: 14 additions & 0 deletions test/error_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -49,3 +49,17 @@
opts.parse %w(--foo)
end
end

describe Slop::MissingRequiredOption do
it "raises when a required option is missing" do
opts = Slop::Options.new
opts.string "-n", "--name", required: true
assert_raises(Slop::MissingRequiredOption) { opts.parse [] }
end

it "does not raise when errors are suppressed" do
opts = Slop::Options.new(suppress_errors: true)
opts.string "-n", "--name", required: true
opts.parse []
end
end

0 comments on commit 2e3f3d0

Please sign in to comment.