Module: Esquema::TypeCaster

Defined in:
lib/esquema/type_caster.rb

Overview

rubocop:disable Style/Documentation

Class Method Summary collapse

Class Method Details

.cast(type, value) ⇒ Object

rubocop:disable Metrics/AbcSize,Metrics/CyclomaticComplexity,Metrics/MethodLength,Metrics/PerceivedComplexity



5
6
7
8
9
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
45
46
47
48
49
50
51
# File 'lib/esquema/type_caster.rb', line 5

def self.cast(type, value) # rubocop:disable Metrics/AbcSize,Metrics/CyclomaticComplexity,Metrics/MethodLength,Metrics/PerceivedComplexity
  case type
  when :string, :text
    value.to_s
  when :integer
    begin
      Integer(value)
    rescue StandardError
      nil
    end
  when :float
    begin
      Float(value)
    rescue StandardError
      nil
    end
  when :number
    if value.to_s.include?(".")
      begin
        Float(value)
      rescue StandardError
        nil
      end
    else
      begin
        Integer(value)
      rescue StandardError
        nil
      end
    end
  when :boolean
    case value
    when true, "true", "1", 1
      true
    when false, "false", "0", 0
      false
    end
  when :array
    Array(value)
  when :object
    value.is_a?(Hash) ? value : nil # or convert as desired
  when :null
    nil if value.nil?
  else
    raise ArgumentError, "Unsupported type: #{type}"
  end
end