Module: Paramore::CastParameters

Defined in:
lib/paramore/cast_parameters.rb

Class Method Summary collapse

Class Method Details

.cast(field, value, name = nil) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/paramore/cast_parameters.rb', line 10

def cast(field, value, name = nil)
  if value.nil?
    if field.nullable? || field.default
      return field.default
    else
      raise Paramore::NilParameter, name
    end
  end

  case field.type
  when Hash
    typecast_hash(field.type, value || {})
  when Array
    typecast_array(field, value)
  else
    typecast_value(field.type, value)
  end
end

.run(field, data) ⇒ Object



6
7
8
# File 'lib/paramore/cast_parameters.rb', line 6

def run(field, data)
  cast(field, data, 'data')
end

.typecast_array(field, array) ⇒ Object



33
34
35
36
37
38
39
# File 'lib/paramore/cast_parameters.rb', line 33

def typecast_array(field, array)
  array
    .reject { |unit| unit.to_s == '' && field.compact? }
    .map do |unit|
      cast(Paramore.field(field.type.first, null: true), unit)
    end
end

.typecast_hash(field, hash) ⇒ Object



29
30
31
# File 'lib/paramore/cast_parameters.rb', line 29

def typecast_hash(field, hash)
  field.to_h { |name, field| [name, cast(field, hash[name], name)] }
end

.typecast_value(type, value) ⇒ Object



41
42
43
# File 'lib/paramore/cast_parameters.rb', line 41

def typecast_value(type, value)
  type.send(Paramore.configuration.type_method_name, value)
end