Module: Toon::Normalizer

Defined in:
lib/toon/normalizer.rb

Class Method Summary collapse

Class Method Details

.array_of_arrays?(value) ⇒ Boolean

Returns:

  • (Boolean)


69
70
71
72
# File 'lib/toon/normalizer.rb', line 69

def array_of_arrays?(value)
  return false unless value.is_a?(Array)
  value.all? { |item| json_array?(item) }
end

.array_of_objects?(value) ⇒ Boolean

Returns:

  • (Boolean)


74
75
76
77
# File 'lib/toon/normalizer.rb', line 74

def array_of_objects?(value)
  return false unless value.is_a?(Array)
  value.all? { |item| json_object?(item) }
end

.array_of_primitives?(value) ⇒ Boolean

Array type detection

Returns:

  • (Boolean)


64
65
66
67
# File 'lib/toon/normalizer.rb', line 64

def array_of_primitives?(value)
  return false unless value.is_a?(Array)
  value.all? { |item| json_primitive?(item) }
end

.json_array?(value) ⇒ Boolean

Returns:

  • (Boolean)


55
56
57
# File 'lib/toon/normalizer.rb', line 55

def json_array?(value)
  value.is_a?(Array)
end

.json_object?(value) ⇒ Boolean

Returns:

  • (Boolean)


59
60
61
# File 'lib/toon/normalizer.rb', line 59

def json_object?(value)
  value.is_a?(Hash)
end

.json_primitive?(value) ⇒ Boolean

Type guards

Returns:

  • (Boolean)


47
48
49
50
51
52
53
# File 'lib/toon/normalizer.rb', line 47

def json_primitive?(value)
  value.nil? ||
    value.is_a?(String) ||
    value.is_a?(Numeric) ||
    value.is_a?(TrueClass) ||
    value.is_a?(FalseClass)
end

.normalize_value(value) ⇒ Object

Normalization (unknown → JSON-compatible value)



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/toon/normalizer.rb', line 11

def normalize_value(value)
  case value
  when nil
    nil
  when String, TrueClass, FalseClass
    value
  when Numeric
    # Float special cases
    if value.is_a?(Float)
      # -0.0 becomes 0
      return 0 if value.zero? && (1.0 / value).negative?
      # NaN and Infinity become nil
      return nil unless value.finite?
    end
    value
  when Symbol
    value.to_s
  when Time
    value.utc.strftime('%Y-%m-%dT%H:%M:%SZ')
  when ->(v) { v.respond_to?(:iso8601) && !v.is_a?(Date) }
    value.iso8601
  when Date
    value.to_time.utc.iso8601
  when Array
    value.map { |v| normalize_value(v) }
  when Set
    value.to_a.map { |v| normalize_value(v) }
  when Hash
    value.each_with_object({}) { |(k, v), h| h[k.to_s] = normalize_value(v) }
  else
    # Fallback: anything else becomes nil (functions, etc.)
    nil
  end
end