diff options
author | William Woodruff <william@tuffbizz.com> | 2017-09-29 18:31:28 -0400 |
---|---|---|
committer | William Woodruff <william@tuffbizz.com> | 2017-09-29 18:55:49 -0400 |
commit | 311cb9fbe94fe09c0dc08a52f5bff169529960ba (patch) | |
tree | 8eb7c8bcba2f7210e47b393dd200c2423dab82c0 /lib | |
parent | ec47929b2ffe986b13701c30f1bbe3018593bc6c (diff) | |
download | slop-311cb9fbe94fe09c0dc08a52f5bff169529960ba.tar.gz |
Support for required options
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`.
Diffstat (limited to 'lib')
-rw-r--r-- | lib/slop/error.rb | 5 | ||||
-rw-r--r-- | lib/slop/option.rb | 6 | ||||
-rw-r--r-- | lib/slop/parser.rb | 9 |
3 files changed, 20 insertions, 0 deletions
diff --git a/lib/slop/error.rb b/lib/slop/error.rb index b02de3b..e024645 100644 --- a/lib/slop/error.rb +++ b/lib/slop/error.rb @@ -32,4 +32,9 @@ module Slop @flag = flag end end + + # Raised when a required option is *not* parsed. + # Suppress with the `suppress_errors` config option. + class MissingRequiredOption < Error + end end diff --git a/lib/slop/option.rb b/lib/slop/option.rb index b8533ae..093b37f 100644 --- a/lib/slop/option.rb +++ b/lib/slop/option.rb @@ -4,6 +4,7 @@ module Slop help: true, tail: false, underscore_flags: true, + required: false, } # An Array of flags this option matches. @@ -101,6 +102,11 @@ module Slop config[:suppress_errors] end + # Returns true if an exception should be raised when this option isn't supplied. + def required? + config[:required] + end + # Returns all flags joined by a comma. Used by the help string. def flag flags.join(", ") diff --git a/lib/slop/parser.rb b/lib/slop/parser.rb index 3cba82b..463e75a 100644 --- a/lib/slop/parser.rb +++ b/lib/slop/parser.rb @@ -80,6 +80,15 @@ module Slop @arguments += ignored_args + if !suppress_errors? + unused_options.each do |o| + if o.config[:required] + pretty_flags = o.flags.map { |f| "`#{f}'" }.join(", ") + raise MissingRequiredOption, "missing required option #{pretty_flags}" + end + end + end + Result.new(self).tap do |result| used_options.each { |o| o.finish(result) } end |