Module: Crystalline

Defined in:
lib/crystalline.rb,
lib/crystalline/types.rb,
lib/crystalline/utils.rb,
lib/crystalline/module.rb,
lib/crystalline/metadata_fields.rb

Overview

typed: false frozen_string_literal: true

Defined Under Namespace

Modules: Enum, MetadataFields, Utils Classes: Array, Boolean, DiscriminatedUnion, Hash, Nilable, Union, Unknown

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.union_strategyObject

Returns the value of attribute union_strategy.



11
12
13
# File 'lib/crystalline/module.rb', line 11

def union_strategy
  @union_strategy
end

Class Method Details

.count_matched_fields(value, raw_data) ⇒ Object



128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
# File 'lib/crystalline/module.rb', line 128

def self.count_matched_fields(value, raw_data)
  matched = 0
  inexact = 0
  unmatched = 0

  if value.is_a?(Crystalline::Unknown)
    return [0, 0, 0]
  elsif value.class.include?(::Crystalline::MetadataFields)
    value.fields.each do |field|
       = field..fetch(:format_json, {})
      lookup = .fetch(:letter_case, nil)&.call
      field_val = value.send(field.name)

      if raw_data.is_a?(::Hash) && lookup && raw_data.key?(lookup)
        if field_val.class.include?(::Crystalline::MetadataFields) && raw_data[lookup].is_a?(::Hash)
          nested_matched, nested_inexact, nested_unmatched = count_matched_fields(field_val, raw_data[lookup])
          matched += nested_matched
          inexact += nested_inexact
          unmatched += nested_unmatched
        else
          matched += 1
          if field_val.respond_to?(:known?) && !field_val.known?
            inexact += 1
          end
        end
      elsif !::Crystalline::Utils.nilable?(field.type)
        unmatched += 1
      end
    end
  elsif value.is_a?(::Array)
    matched = value.length
  elsif value.is_a?(::Hash)
    matched = value.length
  else
    matched = 1
  end

  [matched, inexact, unmatched]
end

.json_encode(val, primitives: true) ⇒ Object



69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/crystalline/module.rb', line 69

def self.json_encode(val, primitives: true)
  if val.class.respond_to?(:enums)
    val.serialize
  elsif val.is_a?(DateTime)
    val.strftime("%Y-%m-%dT%H:%M:%S.%NZ").sub(/(\.\d*[1-9])0+Z\z/, "\\1Z").sub(/\.0+Z\z/, "Z")
  elsif val.nil?
    nil
  elsif primitives
    val.to_s
  else
    val
  end
end

.needs_string_conversion(val) ⇒ Object



26
27
28
# File 'lib/crystalline/module.rb', line 26

def self.needs_string_conversion(val)
  val.class.respond_to?(:enums) || val.is_a?(DateTime) || val.nil?
end

.non_nilable_attr_count(klass) ⇒ Object



168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
# File 'lib/crystalline/module.rb', line 168

def self.non_nilable_attr_count(klass)
  # somewhat sane sort ordering for Union deserialization.
  # All Crystalline objects return the number of non-nilable fields
  # All non-string primitives return 2
  # All arrays and hashes return 1
  # Strings return 0 (since any data can deserialize to a string, it should be our last attempt)
  if klass.respond_to?(:fields)
    return -1 *
      klass.fields.count do |field|
        !::Crystalline::Utils.nilable?(field.type)
      end
  else
    if klass == String
      return 0
    elsif klass.is_a?(T::Types::TypedArray) || klass.is_a?(T::Types::TypedHash)
      return 1
    end

    return 2
  end
end

.to_dict(complex) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
# File 'lib/crystalline/module.rb', line 14

def self.to_dict(complex)
  if complex.is_a?(::Array)
    complex.map { |v| Crystalline.to_dict(v) }
  elsif complex.is_a?(::Hash)
    complex.transform_values { |v| Crystalline.to_dict(v) }
  elsif complex.respond_to?(:class) && complex.class.include?(::Crystalline::MetadataFields)
    complex.to_dict
  else
    json_encode(complex, primitives: false)
  end
end

.to_json(complex) ⇒ Object



30
31
32
# File 'lib/crystalline/module.rb', line 30

def self.to_json(complex)
  JSON.dump(to_dict(complex))
end

.unknown?(value) ⇒ Boolean

Returns:



92
93
94
# File 'lib/crystalline/types.rb', line 92

def self.unknown?(value)
  value.is_a?(Unknown)
end

.unmarshal_json(data, type) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/crystalline/module.rb', line 34

def self.unmarshal_json(data, type)
  if Crystalline::Utils.nilable?(type)
    type = Crystalline::Utils.nilable_of(type)
  end

  if type.is_a?(Crystalline::DiscriminatedUnion)
    type.parse(data)
  elsif type.instance_of?(Class) && type.include?(::Crystalline::MetadataFields)
    type.from_dict(data)
  elsif Crystalline::Utils.union?(type)
    union_types = Crystalline::Utils.get_union_types(type)
    union_types = union_types.sort_by { |klass| Crystalline.non_nilable_attr_count(klass) }

    if Crystalline.union_strategy == :populated_fields
      Crystalline.unmarshal_union_populated_fields(data, union_types)
    else
      Crystalline.unmarshal_union_left_to_right(data, union_types)
    end
  elsif Crystalline::Utils.arr?(type)
    data.map { |v| Crystalline.unmarshal_json(v, Crystalline::Utils.arr_of(type)) }
  elsif Crystalline::Utils.hash?(type)
    data.transform_values { |v| Crystalline.unmarshal_json(v, Crystalline::Utils.hash_of(type)) }
  elsif Crystalline::Utils.nilable?(type) && data == "null"
    nil
  elsif Crystalline::Utils.boolean?(type)
    Crystalline::Utils.to_boolean(data)
  elsif type.is_a?(Class) && type < T::Enum
    type.deserialize(data)
  elsif type.is_a?(Class) && type.respond_to?(:enums) && type.respond_to?(:deserialize)
    type.deserialize(data)
  else
    data
  end
end

.unmarshal_union_left_to_right(data, union_types) ⇒ Object



83
84
85
86
87
88
89
90
91
92
93
94
95
# File 'lib/crystalline/module.rb', line 83

def self.unmarshal_union_left_to_right(data, union_types)
  union_types.each do |union_type|
    return Crystalline.unmarshal_json(data, union_type)
  rescue TypeError
    next
  rescue NoMethodError
    next
  rescue KeyError
    next
  end

  nil
end

.unmarshal_union_populated_fields(data, union_types) ⇒ Object



97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
# File 'lib/crystalline/module.rb', line 97

def self.unmarshal_union_populated_fields(data, union_types)
  best_value = nil
  best_matched = -1
  best_inexact = 0
  best_unmatched = 0

  union_types.each do |union_type|
    value = Crystalline.unmarshal_json(data, union_type)
    matched, inexact, unmatched = count_matched_fields(value, data)

    if best_value.nil? ||
        matched > best_matched ||
        (matched == best_matched && inexact < best_inexact) ||
        (matched == best_matched && inexact == best_inexact && unmatched < best_unmatched)
      best_value = value
      best_matched = matched
      best_inexact = inexact
      best_unmatched = unmatched
    end

  rescue TypeError
    next
  rescue NoMethodError
    next
  rescue KeyError
    next
  end

  best_value
end