Class: Pastore::Params::Validation

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

Overview

Implements the logic of a single param validation

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, type, value, modifier = nil, **options) ⇒ Validation

Returns a new instance of Validation.



29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/pastore/params/validation.rb', line 29

def initialize(name, type, value, modifier = nil, **options)
  @name = name
  @type         = type
  @modifier     = modifier
  @value        = value.nil? ? options[:default] : value
  @required     = (options[:required] == true)                           # default: false
  @allow_blank  = (options[:allow_blank].nil? || options[:allow_blank])  # default: true
  @allowed_values = options[:in]
  @exclude_values = options[:exclude]

  @errors = []

  validate!
end

Instance Attribute Details

#errorsObject (readonly)

Returns the value of attribute errors.



27
28
29
# File 'lib/pastore/params/validation.rb', line 27

def errors
  @errors
end

#valueObject (readonly)

Returns the value of attribute value.



27
28
29
# File 'lib/pastore/params/validation.rb', line 27

def value
  @value
end

Class Method Details

.validate!(name, type, value, modifier = nil, **options) ⇒ Object

Validates the value based on the given type and values with the appropriate validator.



14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/pastore/params/validation.rb', line 14

def self.validate!(name, type, value, modifier = nil, **options)
  case type
  when 'string'  then Pastore::Params::StringValidation.new(name, value, modifier, **options)
  when 'number'  then Pastore::Params::NumberValidation.new(name, value, modifier, **options)
  when 'boolean' then Pastore::Params::BooleanValidation.new(name, value, modifier, **options)
  when 'object'  then Pastore::Params::ObjectValidation.new(name, value, modifier, **options)
  when 'date'    then Pastore::Params::DateValidation.new(name, value, modifier, **options)
  when 'any'     then Validation.new(name, 'any', value, modifier, **options)
  else
    raise Pastore::Params::InvalidValidationTypeError, "Invalid validation type: #{type}"
  end
end

Instance Method Details

#add_error(error_type, message) ⇒ Object

Adds an error to the list of errors.



55
56
57
# File 'lib/pastore/params/validation.rb', line 55

def add_error(error_type, message)
  @errors << { type: 'param', name: @name, value: @value, error: error_type, message: message }
end

#required?Boolean

Returns true if the value is required, false otherwise.

Returns:

  • (Boolean)


50
51
52
# File 'lib/pastore/params/validation.rb', line 50

def required?
  @required
end

#valid?Boolean

Returns true if the value is valid, false otherwise.

Returns:

  • (Boolean)


45
46
47
# File 'lib/pastore/params/validation.rb', line 45

def valid?
  @errors.empty?
end