Class: CommandMapper::Types::Str

Inherits:
Type
  • Object
show all
Defined in:
lib/command_mapper/types/str.rb

Overview

Represents an arbitrary string value.

Instance Method Summary collapse

Methods inherited from Type

#format

Constructor Details

#initialize(allow_empty: false, allow_blank: false) ⇒ Str

Initializes the value.

Parameters:

  • allow_empty (Boolean) (defaults to: false)

    Specifies whether the argument may accept empty values.

  • allow_blank (Boolean) (defaults to: false)

    Specifies whether the argument may accept blank values.


18
19
20
21
# File 'lib/command_mapper/types/str.rb', line 18

def initialize(allow_empty: false, allow_blank: false)
  @allow_empty = allow_empty
  @allow_blank = allow_blank
end

Instance Method Details

#allow_blank?Boolean

Specifies whether the option's value may accept blank values.

Returns:

  • (Boolean)

41
42
43
# File 'lib/command_mapper/types/str.rb', line 41

def allow_blank?
  @allow_blank
end

#allow_empty?Boolean

Specifies whether the option's value may accept empty values.

Returns:

  • (Boolean)

30
31
32
# File 'lib/command_mapper/types/str.rb', line 30

def allow_empty?
  @allow_empty
end

#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