Method: CommandMapper::Types::Str#validate

Defined in:
lib/command_mapper/types/str.rb

#validate(value) ⇒ true, (false, String)

Validates the given value.

Parameters:

  • value (Object)

    The given value to validate.

Returns:

  • (true, (false, String))

    Returns true if the value is considered valid, or false and a validation message if the value is not valid.

    • If nil is given and a value is required, then false will be returned.
    • If an empty value is given and empty values are not allowed, then false will be returned.
    • If an empty value is given and blank values are not allowed, then false will be returned.


63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/command_mapper/types/str.rb', line 63

def validate(value)
  case value
  when nil
    unless allow_empty?
      return [false, "cannot be nil"]
    end
  when Enumerable
    return [false, "cannot convert a #{value.class} into a String (#{value.inspect})"]
  else
    unless value.respond_to?(:to_s)
      return [false, "does not define a #to_s method (#{value.inspect})"]
    end

    string = value.to_s

    if string.empty?
      unless allow_empty?
        return [false, "does not allow an empty value"]
      end
    elsif string =~ /\A\s+\z/
      unless allow_blank?
        return [false, "does not allow a blank value (#{value.inspect})"]
      end
    end
  end

  return true
end