Sha256: 3a0e004bb19fe1031d590f3a782a916adaf34b3186a55a96a967eabc56589434

Contents?: true

Size: 979 Bytes

Versions: 5

Compression:

Stored size: 979 Bytes

Contents

module OptParseValidator
  # Implementation of the Choice Option
  class OptChoice < OptBase
    # @param [ Array ] option See OptBase#new
    # @param [ Hash ] attrs
    #   :choices [ Array ] The available choices (mandatory)
    #   :case_sensitive [ Boolean ] Default: false
    def initialize(option, attrs = {})
      fail 'The :choices attribute is mandatory' unless attrs.key?(:choices)
      fail 'The :choices attribute must be an array' unless attrs[:choices].is_a?(Array)

      super(option, attrs)
    end

    # @return [ String ]
    # If :case_sensitive if false (or nil), the downcased value of the choice
    # will be returned
    def validate(value)
      value = value.to_s

      unless attrs[:case_sensitive]
        value.downcase!
        choices.map!(&:downcase)
      end

      fail "'#{value}' is not a valid choice, expected one " \
           "of the followings: #{choices.join(',')}" unless choices.include?(value)

      value
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
opt_parse_validator-0.0.11 lib/opt_parse_validator/opts/choice.rb
opt_parse_validator-0.0.10 lib/opt_parse_validator/opts/choice.rb
opt_parse_validator-0.0.9 lib/opt_parse_validator/opts/choice.rb
opt_parse_validator-0.0.8 lib/opt_parse_validator/opts/choice.rb
opt_parse_validator-0.0.7 lib/opt_parse_validator/opts/choice.rb