Class: ActionSpec::Schema::TypeCaster

Inherits:
Object
  • Object
show all
Defined in:
lib/action_spec/schema/type_caster.rb

Defined Under Namespace

Classes: CastError

Class Method Summary collapse

Class Method Details

.cast(type, value) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/action_spec/schema/type_caster.rb', line 16

def cast(type, value)
  return value if value.nil?

  normalized = normalize(type)
  return cast_object(value) if normalized == :object
  return cast_file(value) if normalized == :file
  return cast_boolean(value) if normalized == :boolean
  return cast_integer(value) if normalized == :integer
  return cast_float(value) if normalized == :float
  return cast_decimal(value) if normalized == :decimal

  active_model_type_for(normalized).cast(value).tap do |casted|
    raise CastError, normalized if casted.nil? && !value.nil?
  end
end

.normalize(type) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/action_spec/schema/type_caster.rb', line 32

def normalize(type)
  return :boolean if boolean_type?(type)
  return :string if type == String
  return :integer if type == Integer
  return :float if type == Float
  return :decimal if type == BigDecimal
  return :date if type == Date
  return :datetime if [DateTime, ActiveSupport::TimeWithZone].include?(type)
  return :time if type == Time
  return :string if type == Symbol
  return :file if type == File
  return :object if [Hash, Object].include?(type)

  type
end