Module: Sinatra::ParamValidator::Parameter::Common

Included in:
Array, Boolean, Date, Float, Hash, Integer, String, Time
Defined in:
lib/sinatra/param_validator/parameter/common.rb

Overview

Common validation methods shared between parameters

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#coercedObject (readonly)

Returns the value of attribute coerced.



8
9
10
# File 'lib/sinatra/param_validator/parameter/common.rb', line 8

def coerced
  @coerced
end

#errorsObject (readonly)

Returns the value of attribute errors.



8
9
10
# File 'lib/sinatra/param_validator/parameter/common.rb', line 8

def errors
  @errors
end

Instance Method Details

#in(options) ⇒ Object



39
40
41
# File 'lib/sinatra/param_validator/parameter/common.rb', line 39

def in(options)
  @errors.push "Parameter must be within #{options}" unless in? options
end

#initialize(value, **options) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/sinatra/param_validator/parameter/common.rb', line 10

def initialize(value, **options)
  @errors = []
  @options = options

  begin
    @coerced = coerce value
  rescue ArgumentError
    @errors.push "'#{value}' is not a valid #{self.class}"
    return
  end

  validate_options
  validate unless nil_and_ok?
end

#is(option_value) ⇒ Object



53
54
55
# File 'lib/sinatra/param_validator/parameter/common.rb', line 53

def is(option_value)
  @errors.push "Parameter must be #{option_value}" unless @coerced == option_value
end

#nillable(_) ⇒ Object



57
58
59
# File 'lib/sinatra/param_validator/parameter/common.rb', line 57

def nillable(_)
  # Does nothing. Allows other tests to ignore nil values if present in the options
end

#required(enabled) ⇒ Object



66
67
68
# File 'lib/sinatra/param_validator/parameter/common.rb', line 66

def required(enabled)
  @errors.push 'Parameter is required' if enabled && @coerced.nil?
end

#valid?Boolean

Returns:



25
26
27
# File 'lib/sinatra/param_validator/parameter/common.rb', line 25

def valid?
  @errors.empty?
end