Skip to content

Commit

Permalink
- Add 'required' option support:
Browse files Browse the repository at this point in the history
    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.
  • Loading branch information
jordansissel committed May 4, 2012
1 parent 3433ae4 commit 967997f
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
14 changes: 14 additions & 0 deletions lib/clamp/option.rb
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,16 @@ def initialize(switches, type, description, options = {})
if options.has_key?(:environment_variable)
@environment_variable = options[:environment_variable]
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
Expand All @@ -33,6 +43,10 @@ def handles?(switch)
recognised_switches.member?(switch)
end

def required?
@required
end

def flag?
@type == :flag
end
Expand Down
13 changes: 13 additions & 0 deletions lib/clamp/option/parsing.rb
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,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
Expand Down

0 comments on commit 967997f

Please sign in to comment.