Module: Lutaml::Model::Serialize::ClassMethods

Defined in:
lib/lutaml/model/serialize.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#attributesObject

Returns the value of attribute attributes.



22
23
24
# File 'lib/lutaml/model/serialize.rb', line 22

def attributes
  @attributes
end

#mappingsObject

Returns the value of attribute mappings.



22
23
24
# File 'lib/lutaml/model/serialize.rb', line 22

def mappings
  @mappings
end

Instance Method Details

#apply_child_mappings(hash, child_mappings) ⇒ Object



236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
# File 'lib/lutaml/model/serialize.rb', line 236

def apply_child_mappings(hash, child_mappings)
  return hash unless child_mappings

  hash.map do |key, value|
    child_mappings.to_h do |attr_name, path|
      attr_value = if path == :key
                     key
                   elsif path == :value
                     value
                   else
                     path = [path] unless path.is_a?(Array)
                     value.dig(*path.map(&:to_s))
                   end

      [attr_name, attr_value]
    end
  end
end

#apply_mappings(doc, format) ⇒ Object



282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
# File 'lib/lutaml/model/serialize.rb', line 282

def apply_mappings(doc, format)
  return apply_xml_mapping(doc) if format == :xml

  mappings = mappings_for(format).mappings
  mappings.each_with_object(Lutaml::Model::MappingHash.new) do |rule, hash|
    attr = if rule.delegate
             attributes[rule.delegate].type.attributes[rule.to]
           else
             attributes[rule.to]
           end

    raise "Attribute '#{rule.to}' not found in #{self}" unless attr

    value = if rule.custom_methods[:from]
              new.send(rule.custom_methods[:from], hash, doc)
            elsif doc.key?(rule.name) || doc.key?(rule.name.to_sym)
              doc[rule.name] || doc[rule.name.to_sym]
            else
              attr.default
            end

    value = apply_child_mappings(value, rule.child_mappings)

    if attr.collection?
      value = (value || []).map do |v|
        attr.type <= Serialize ? attr.type.apply_mappings(v, format) : v
      end
    elsif value.is_a?(Hash) && attr.type != Lutaml::Model::Type::Hash
      value = attr.type.apply_mappings(value, format)
    end

    if rule.delegate
      hash[rule.delegate] ||= {}
      hash[rule.delegate][rule.to] = value
    else
      hash[rule.to] = value
    end
  end
end

#apply_xml_mapping(doc, caller_class: nil, mixed_content: false) ⇒ Object



322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
# File 'lib/lutaml/model/serialize.rb', line 322

def apply_xml_mapping(doc, caller_class: nil, mixed_content: false)
  return unless doc

  mappings = mappings_for(:xml).mappings

  if doc.is_a?(Array)
    raise "May be `collection: true` is" \
          "missing for #{self} in #{caller_class}"
  end

  mapping_hash = Lutaml::Model::MappingHash.new
  mapping_hash.item_order = doc.item_order
  mapping_hash.ordered = mappings_for(:xml).mixed_content? || mixed_content

  mappings.each_with_object(mapping_hash) do |rule, hash|
    attr = attributes[rule.to]
    raise "Attribute '#{rule.to}' not found in #{self}" unless attr

    is_content_mapping = rule.name.nil?
    value = if is_content_mapping
              doc["text"]
            else
              doc[rule.name.to_s] || doc[rule.name.to_sym]
            end

    if attr.collection?
      if value && !value.is_a?(Array)
        value = [value]
      end

      value = (value || []).map do |v|
        if attr.type <= Serialize
          attr.type.apply_xml_mapping(v, caller_class: self, mixed_content: rule.mixed_content)
        elsif v.is_a?(Hash)
          v["text"]
        else
          v
        end
      end
    elsif attr.type <= Serialize
      value = attr.type.apply_xml_mapping(value, caller_class: self, mixed_content: rule.mixed_content)
    else
      if value.is_a?(Hash) && attr.type != Lutaml::Model::Type::Hash
        value = value["text"]
      end

      value = attr.type.cast(value) unless is_content_mapping
    end

    hash[rule.to] = value
  end
end

#attr_value(attrs, name, attr_rule) ⇒ Object



191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
# File 'lib/lutaml/model/serialize.rb', line 191

def attr_value(attrs, name, attr_rule)
  value = if attrs.key?(name)
            attrs[name]
          elsif attrs.key?(name.to_sym)
            attrs[name.to_sym]
          elsif attrs.key?(name.to_s)
            attrs[name.to_s]
          else
            attr_rule.default
          end

  if attr_rule.collection? || value.is_a?(Array)
    (value || []).map do |v|
      if v.is_a?(Hash)
        attr_rule.type.new(v)
      else
        # TODO: This code is problematic because Type.cast does not know
        # about all the types.
        Lutaml::Model::Type.cast(
          v, attr_rule.type
        )
      end
    end
  elsif value.is_a?(Hash) && attr_rule.type != Lutaml::Model::Type::Hash
    generate_model_object(attr_rule.type, value)
  else
    # TODO: This code is problematic because Type.cast does not know
    # about all the types.
    Lutaml::Model::Type.cast(value, attr_rule.type)
  end
end

#attr_value_valid?(name, value) ⇒ Boolean

Check if the value to be assigned is valid for the attribute

Returns:

  • (Boolean)


62
63
64
65
66
67
68
69
70
# File 'lib/lutaml/model/serialize.rb', line 62

def attr_value_valid?(name, value)
  attr = attributes[name]

  return true unless attr.options[:values]

  # If value validation failed but there is a default value, do not
  # raise a validation error
  attr.options[:values].include?(value || attr.default)
end

#attribute(name, type, options = {}) ⇒ Object

Define an attribute for the model



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/lutaml/model/serialize.rb', line 44

def attribute(name, type, options = {})
  attr = Attribute.new(name, type, options)
  attributes[name] = attr

  define_method(name) do
    instance_variable_get(:"@#{name}")
  end

  define_method(:"#{name}=") do |value|
    unless self.class.attr_value_valid?(name, value)
      raise Lutaml::Model::InvalidValueError.new(name, value, options[:values])
    end

    instance_variable_set(:"@#{name}", value)
  end
end

#default_mappings(format) ⇒ Object



223
224
225
226
227
228
229
230
231
232
233
234
# File 'lib/lutaml/model/serialize.rb', line 223

def default_mappings(format)
  klass = format == :xml ? XmlMapping : KeyValueMapping
  klass.new.tap do |mapping|
    attributes&.each do |name, attr|
      mapping.map_element(
        name.to_s,
        to: name,
        render_nil: attr.render_nil?,
      )
    end
  end
end

#ensure_utf8(value) ⇒ Object



375
376
377
378
379
380
381
382
383
384
385
386
387
388
# File 'lib/lutaml/model/serialize.rb', line 375

def ensure_utf8(value)
  case value
  when String
    value.encode("UTF-8", invalid: :replace, undef: :replace, replace: "")
  when Array
    value.map { |v| ensure_utf8(v) }
  when Hash
    value.transform_keys do |k|
      ensure_utf8(k)
    end.transform_values { |v| ensure_utf8(v) }
  else
    value
  end
end

#generate_hash_from_child_mappings(value, child_mappings) ⇒ Object



255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
# File 'lib/lutaml/model/serialize.rb', line 255

def generate_hash_from_child_mappings(value, child_mappings)
  return value unless child_mappings

  hash = {}

  value.each do |child_obj|
    map_key = nil
    map_value = {}
    child_mappings.each do |attr_name, path|
      if path == :key
        map_key = child_obj.send(attr_name)
      elsif path == :value
        map_value = child_obj.send(attr_name)
      else
        path = [path] unless path.is_a?(Array)
        path[0...-1].inject(map_value) do |acc, k|
          acc[k.to_s] ||= {}
        end.public_send(:[]=, path.last.to_s, child_obj.send(attr_name))
      end
    end
    # hash[mapping.name] ||= {}
    hash[map_key] = map_value
  end

  hash
end

#generate_model_object(type, mapped_attrs) ⇒ Object



177
178
179
180
181
182
183
184
185
186
187
188
189
# File 'lib/lutaml/model/serialize.rb', line 177

def generate_model_object(type, mapped_attrs)
  return type.model.new(mapped_attrs) if self == model

  instance = type.model.new

  type.attributes.each do |name, attr|
    value = attr_value(mapped_attrs, name, attr)

    instance.send(:"#{name}=", ensure_utf8(value))
  end

  instance
end

#handle_delegate(instance, rule, hash) ⇒ Object



149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
# File 'lib/lutaml/model/serialize.rb', line 149

def handle_delegate(instance, rule, hash)
  name = rule.to
  value = instance.send(rule.delegate).send(name)
  return if value.nil? && !rule.render_nil

  attribute = instance.send(rule.delegate).class.attributes[name]
  hash[rule.from] = case value
                    when Array
                      value.map do |v|
                        if v.is_a?(Serialize)
                          hash_representation(v, format, options)
                        else
                          attribute.type.serialize(v)
                        end
                      end
                    else
                      if value.is_a?(Serialize)
                        hash_representation(value, format, options)
                      else
                        attribute.type.serialize(value)
                      end
                    end
end

#hash_representation(instance, format, options = {}) ⇒ Object



110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
# File 'lib/lutaml/model/serialize.rb', line 110

def hash_representation(instance, format, options = {})
  only = options[:only]
  except = options[:except]
  mappings = mappings_for(format).mappings

  mappings.each_with_object({}) do |rule, hash|
    name = rule.to
    next if except&.include?(name) || (only && !only.include?(name))

    next handle_delegate(instance, rule, hash) if rule.delegate

    value = if rule.custom_methods[:to]
              instance.send(rule.custom_methods[:to], instance, instance.send(name))
            else
              instance.send(name)
            end

    next if value.nil? && !rule.render_nil

    attribute = attributes[name]

    hash[rule.from] = if rule.child_mappings
                        generate_hash_from_child_mappings(value, rule.child_mappings)
                      elsif value.is_a?(Array)
                        value.map do |v|
                          if attribute.type <= Serialize
                            attribute.type.hash_representation(v, format, options)
                          else
                            attribute.type.serialize(v)
                          end
                        end
                      elsif attribute.type <= Serialize
                        attribute.type.hash_representation(value, format, options)
                      else
                        attribute.type.serialize(value)
                      end
  end
end

#inherited(subclass) ⇒ Object



24
25
26
27
28
29
30
31
32
33
# File 'lib/lutaml/model/serialize.rb', line 24

def inherited(subclass)
  super

  @mappings ||= {}
  @attributes ||= {}

  subclass.instance_variable_set(:@attributes, @attributes.dup)
  subclass.instance_variable_set(:@mappings, @mappings.dup)
  subclass.instance_variable_set(:@model, subclass)
end

#mappings_for(format) ⇒ Object



173
174
175
# File 'lib/lutaml/model/serialize.rb', line 173

def mappings_for(format)
  mappings[format] || default_mappings(format)
end

#model(klass = nil) ⇒ Object



35
36
37
38
39
40
41
# File 'lib/lutaml/model/serialize.rb', line 35

def model(klass = nil)
  if klass
    @model = klass
  else
    @model
  end
end