Module: OpenapiParameters::Converter

Defined in:
lib/openapi_parameters/converter.rb

Overview

Tries to convert a request parameter value (string) to the type specified in the JSON Schema.

Class Method Summary collapse

Class Method Details

.convert(value, schema) ⇒ Object

Parameters:

  • value (String, Hash, Array)

    the value to convert

  • schema (Hash)

    the schema to use for conversion.



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
40
41
42
43
44
# File 'lib/openapi_parameters/converter.rb', line 10

def convert(value, schema) # rubocop:disable Metrics
  return if value.nil?
  return value if schema.nil?

  case type(schema)
  when 'integer'
    begin
      Integer(value, 10)
    rescue StandardError
      value
    end
  when 'number'
    begin
      Float(value)
    rescue StandardError
      value
    end
  when 'boolean'
    if value == 'true'
      true
    else
      value == 'false' ? false : value
    end
  when 'object'
    convert_object(value, schema)
  when 'array'
    convert_array(value, schema)
  else
    if schema['properties']
      convert_object(value, schema)
    else
      value
    end
  end
end

.convert_object(value, schema) ⇒ Object



46
47
48
49
50
51
52
# File 'lib/openapi_parameters/converter.rb', line 46

def convert_object(value, schema)
  return value unless value.is_a?(Hash)

  value.each_with_object({}) do |(key, val), hsh|
    hsh[key] = convert(val, schema['properties']&.fetch(key, nil))
  end
end