From d878c74aa460a6acd933ce22675d8487e69222c7 Mon Sep 17 00:00:00 2001 From: Jordan Sissel Date: Mon, 30 Apr 2012 15:14:21 -0700 Subject: [PATCH] - Add 'required' option support: option "--foo", "BAR", "Some description", :required => true Notes: - :required and :default are mutually exclusive as a sanity check. - :required conflicts with :flag options since that doesn't make sense either. --- lib/clamp/option.rb | 14 ++++++++++++++ lib/clamp/option/parsing.rb | 13 +++++++++++++ 2 files changed, 27 insertions(+) diff --git a/lib/clamp/option.rb b/lib/clamp/option.rb index 3491a9e..1884c10 100644 --- a/lib/clamp/option.rb +++ b/lib/clamp/option.rb @@ -17,6 +17,16 @@ def initialize(switches, type, description, options = {}) if options.has_key?(:env) @environment_variable = options[:env] end + if options.has_key?(:required) + @required = options[:required] + # Do some light validation for conflicting settings. + if options.has_key?(:default) + raise ArgumentError, "Specifying a :default value also :required doesn't make sense" + end + if type == :flag + raise ArgumentError, "A required flag (boolean) doesn't make sense." + end + end end attr_reader :switches, :type @@ -33,6 +43,10 @@ def handles?(switch) recognised_switches.member?(switch) end + def required? + @required + end + def flag? @type == :flag end diff --git a/lib/clamp/option/parsing.rb b/lib/clamp/option/parsing.rb index 0d1670c..300183a 100644 --- a/lib/clamp/option/parsing.rb +++ b/lib/clamp/option/parsing.rb @@ -48,6 +48,19 @@ def parse_options end end + + # Verify that all required options are present + self.class.recognised_options.each do |option| + # If this option is required and the value is nil, there's an error. + if option.required? and send(option.attribute_name).nil? + message = "option '#{option.switches.first}'" + if option.environment_variable + message += " (or env #{option.environment_variable})" + end + message += " is required" + signal_usage_error message + end + end end def parse_environment_options