Class: CliMiami::Validation

Inherits:
Object
  • Object
show all
Defined in:
lib/cli_miami/validation.rb

Overview

validates user input values against their expected type

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(initial_value, options) ⇒ Validation

validates string provided by the user

rubocop:disable Metrics/AbcSize, Metrics/MethodLength


10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/cli_miami/validation.rb', line 10

def initialize initial_value, options
  @options = CliMiami.get_options options
  @value = initial_value
  @valid = true
  @error = nil

  # convert
  # only attempt to convert strings
  # if not a string, skip conversion and go straight to validation
  if initial_value.is_a? String
    begin
      @value = send("convert_string_to_#{options[:type]}", initial_value, @options)
    rescue
      @error = CliMiami::Error.new(initial_value, @options, :convert).message
      @valid = false
    end
  end

  return if @value.nil? || !@valid

  # validate
  begin
    # keep all values the same unless validation fails
    send "validate_#{options[:type]}", @value, @options
  rescue => error
    # if validation fails, set values, including error to the specific validation error
    @error = error.to_s
    @valid = false
  end
end

Instance Attribute Details

#errorObject (readonly)

Returns the value of attribute error


5
6
7
# File 'lib/cli_miami/validation.rb', line 5

def error
  @error
end

#validObject (readonly)

Returns the value of attribute valid


5
6
7
# File 'lib/cli_miami/validation.rb', line 5

def valid
  @valid
end

#valueObject (readonly)

Returns the value of attribute value


5
6
7
# File 'lib/cli_miami/validation.rb', line 5

def value
  @value
end

Instance Method Details

#valid?Boolean

rubocop:enable Metrics/AbcSize, Metrics/MethodLength

Returns:


42
43
44
# File 'lib/cli_miami/validation.rb', line 42

def valid?
  @valid
end