Class: Pastvu::TypeCheck

Inherits:
Object
  • Object
show all
Defined in:
lib/pastvu/params_validator/type_check.rb

Constant Summary collapse

ALLOWED_TYPES =
{
  cid:        Integer,
  distance:   Integer, # <= 1000000 (meters)
  except:     Integer,
  geo:        Array, # [lat and lon]
  geometry:   Hash, # [geoJSON]
  isPainting: [TrueClass, FalseClass],
  limit:      Integer, # <= 30
  localWork:  [TrueClass, FalseClass],
  skip:       Integer,
  type:       String, # "photo" or "painting"
  year:       Integer,
  year2:      Integer,
  z:          Integer
}

Class Method Summary collapse

Class Method Details

.correct_type?(param, type) ⇒ Boolean

Returns:

  • (Boolean)


40
41
42
43
44
45
46
# File 'lib/pastvu/params_validator/type_check.rb', line 40

def self.correct_type?(param, type)
  if type.instance_of?(Array)
    type.any? { |type| param.instance_of?(type) }
  else
    param.instance_of?(type)
  end
end

.report_errors(errors) ⇒ Object

Raises:

  • (ArgumentError)


32
33
34
35
36
37
38
# File 'lib/pastvu/params_validator/type_check.rb', line 32

def self.report_errors(errors)
  report = errors.map do |k, v|
    "\n#{k}: #{v[0]} must be #{v[1]}"
  end.join(", ")

  raise ArgumentError, "expect correct params type\n #{report}"
end

.validate(params) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/pastvu/params_validator/type_check.rb', line 19

def self.validate(params)
  errors = {}
  ALLOWED_TYPES.each do |k, type|
    param = params[k]
    next if param.nil?
    next if self.correct_type? param, type

    errors.merge!({ k.to_sym => [param, type] })
  end

  errors.empty? ? true : report_errors(errors)
end