Class: Lutaml::Xml::Mapping

Inherits:
Model::Mapping show all
Defined in:
lib/lutaml/xml/mapping.rb

Constant Summary collapse

TYPES =
{
  attribute: :map_attribute,
  element: :map_element,
  content: :map_content,
  all_content: :map_all,
  processing_instruction: :map_processing_instruction,
}.freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Model::Mapping

#add_listener, #all_listeners, #inherit_from, #listeners_for, #omit_element, #omit_listener, #parent_mapping

Constructor Details

#initializeMapping

Returns a new instance of Mapping.



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/lutaml/xml/mapping.rb', line 57

def initialize
  super

  @elements = {}
  @attributes = {}
  @element_sequence = []
  @content_mapping = nil
  @raw_mapping = nil
  @mixed_content = false
  @xml_space = nil
  @format = :xml
  @register_elements = ::Hash.new { |h, k| h[k] = {} }
  @register_attributes = ::Hash.new { |h, k| h[k] = {} }
  @register_element_sequences = ::Hash.new { |h, k| h[k] = [] }
  @consolidation_maps = []
  @element_name = nil
  @namespace_class = nil
  @documentation_text = nil
  @type_name_value = nil
  @namespace_scope = []
  @namespace_scope_config = []
  @mapper_class = nil
  @importing_mappings = false
  @attributes_with_methods_defined = Set.new
  @processing_instruction_mappings = []

  # Performance: Caches for finalized mapping queries
  @cached_elements = {}
  @cached_attributes = {}
  @cached_mappings = {}
  @finalized = false
end

Instance Attribute Details

#consolidation_mapsObject (readonly)

Returns the value of attribute consolidation_maps.



41
42
43
# File 'lib/lutaml/xml/mapping.rb', line 41

def consolidation_maps
  @consolidation_maps
end

#documentation_textObject (readonly)

Returns the value of attribute documentation_text.



41
42
43
# File 'lib/lutaml/xml/mapping.rb', line 41

def documentation_text
  @documentation_text
end

#element_nameObject (readonly)

Returns the value of attribute element_name.



41
42
43
# File 'lib/lutaml/xml/mapping.rb', line 41

def element_name
  @element_name
end

#element_sequenceObject (readonly)

Returns the value of attribute element_sequence.



41
42
43
# File 'lib/lutaml/xml/mapping.rb', line 41

def element_sequence
  @element_sequence
end

#mapper_classObject (readonly)

Returns the value of attribute mapper_class.



41
42
43
# File 'lib/lutaml/xml/mapping.rb', line 41

def mapper_class
  @mapper_class
end

#mappings_importedObject (readonly)

Returns the value of attribute mappings_imported.



41
42
43
# File 'lib/lutaml/xml/mapping.rb', line 41

def mappings_imported
  @mappings_imported
end

#namespace_classObject (readonly)

Returns the value of attribute namespace_class.



41
42
43
# File 'lib/lutaml/xml/mapping.rb', line 41

def namespace_class
  @namespace_class
end

#namespace_paramObject (readonly)

Returns the value of attribute namespace_param.



41
42
43
# File 'lib/lutaml/xml/mapping.rb', line 41

def namespace_param
  @namespace_param
end

#namespace_prefixObject (readonly)

Returns the value of attribute namespace_prefix.



41
42
43
# File 'lib/lutaml/xml/mapping.rb', line 41

def namespace_prefix
  @namespace_prefix
end

#namespace_scope(namespaces = nil) ⇒ Array<Class> (readonly)

Set the namespace scope for this mapping

Controls which namespaces are declared at the root element level versus being declared locally on each element that uses them.

Namespaces listed in namespace_scope will be declared once on the root element. Namespaces not listed will be declared locally on elements where they are used.

Examples:

Simple array of namespace classes (all default to :auto)

namespace_scope [VcardNamespace, DctermsNamespace, DcElementsNamespace]

Per-namespace declaration control

namespace_scope [
  { namespace: VcardNamespace, declare: :always },
  { namespace: DctermsNamespace, declare: :auto },
  XsiNamespace  # Can mix hash and class entries
]

Parameters:

  • namespaces (Array<Class>, Array<Hash>) (defaults to: nil)

    array of XmlNamespace classes or hashes with :namespace and :declare keys

Returns:

  • (Array<Class>)

    the current namespace scope



434
435
436
# File 'lib/lutaml/xml/mapping.rb', line 434

def namespace_scope
  @namespace_scope
end

#namespace_scope_configObject

Returns the value of attribute namespace_scope_config.



1254
1255
1256
# File 'lib/lutaml/xml/mapping.rb', line 1254

def namespace_scope_config
  @namespace_scope_config
end

#namespace_uriObject (readonly)

Returns the value of attribute namespace_uri.



41
42
43
# File 'lib/lutaml/xml/mapping.rb', line 41

def namespace_uri
  @namespace_uri
end

#processing_instruction_mappingsObject (readonly)

Returns the value of attribute processing_instruction_mappings.



41
42
43
# File 'lib/lutaml/xml/mapping.rb', line 41

def processing_instruction_mappings
  @processing_instruction_mappings
end

#root_elementObject (readonly)

Returns the value of attribute root_element.



41
42
43
# File 'lib/lutaml/xml/mapping.rb', line 41

def root_element
  @root_element
end

#type_name_valueObject (readonly)

Returns the value of attribute type_name_value.



41
42
43
# File 'lib/lutaml/xml/mapping.rb', line 41

def type_name_value
  @type_name_value
end

#xml_space(value = nil) ⇒ Symbol? (readonly)

Control the xml:space attribute for this element

When set to :preserve, automatically adds ‘xml:space=“preserve”` during serialization. When set to :default, adds `xml:space=“default”`. When false or nil, no xml:space attribute is added.

Examples:

Add xml:space=“preserve”

xml do
  element "text"
  mixed_content
  xml_space :preserve  # Adds xml:space="preserve"
end

Add xml:space=“default”

xml do
  element "text"
  xml_space :default
end

Parameters:

  • value (Symbol, Boolean, nil) (defaults to: nil)

    :preserve, :default, false, or nil

Returns:

  • (Symbol, nil)

    the xml_space value



232
233
234
# File 'lib/lutaml/xml/mapping.rb', line 232

def xml_space
  @xml_space
end

Class Method Details

.xml(&block) ⇒ Lutaml::Xml::Mapping

Class-level XML DSL for reusable mapping classes.

When a subclass of Lutaml::Xml::Mapping uses ‘xml do…end` in its class body, this method creates an instance and evaluates the block.

Examples:

class BaseMapping < Lutaml::Xml::Mapping
  xml do
    namespace_scope [MyNamespace]
    map_element "Foo", to: :foo
  end
end

Parameters:

  • block (Proc)

    DSL block with map_element, namespace_scope, etc.

Returns:



27
28
29
30
31
# File 'lib/lutaml/xml/mapping.rb', line 27

def self.xml(&block)
  @xml_instance ||= new
  @xml_instance.instance_eval(&block) if block
  @xml_instance
end

.xml_mapping_instanceLutaml::Xml::Mapping?

Get the shared XML mapping instance for this mapping class. Created lazily via the xml() class method.

Returns:



37
38
39
# File 'lib/lutaml/xml/mapping.rb', line 37

def self.xml_mapping_instance
  @xml_instance
end

Instance Method Details

#attributes(register_id = nil) ⇒ Object



1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
# File 'lib/lutaml/xml/mapping.rb', line 1032

def attributes(register_id = nil)
  reg_key = register_id || :default
  cached = @cached_attributes[reg_key]
  return cached if cached

  result = mapping_attributes_hash(register_id).values.flat_map do |v|
    v.is_a?(Array) ? v : [v]
  end
  @cached_attributes[reg_key] = result.freeze if @finalized
  result
end

#attributes_hashObject



1240
1241
1242
# File 'lib/lutaml/xml/mapping.rb', line 1240

def attributes_hash
  @attributes
end

#attributes_to_dupObject



1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
# File 'lib/lutaml/xml/mapping.rb', line 1315

def attributes_to_dup
  @attributes_to_dup ||= %i[
    @content_mapping
    @raw_mapping
    @element_sequence
    @attributes
    @elements
    @processing_instruction_mappings
    @register_elements
    @register_attributes
    @register_element_sequences
    @mappings_imported
    @sequence_importable_mappings
    @consolidation_maps
  ]
end

#consolidate_map(by:, to:, group_class: nil) { ... } ⇒ ConsolidationMap

Declare consolidation rules for this mapping.

Creates a ConsolidationMap that describes how sibling elements are grouped into structured model instances.

Parameters:

  • by (Symbol)

    grouping criterion (:attr_name or :pattern)

  • to (Symbol)

    target attribute name on the Collection

  • group_class (Class) (defaults to: nil)

    the GroupClass to instantiate (optional, resolved from Organization)

Yields:

  • Builder block with gather/dispatch_by or map_element/map_content

Returns:

  • (ConsolidationMap)


810
811
812
813
814
815
# File 'lib/lutaml/xml/mapping.rb', line 810

def consolidate_map(by:, to:, group_class: nil, &)
  builder = ::Lutaml::Model::ConsolidationMap::Builder.new(by, to,
                                                           group_class)
  builder.instance_eval(&)
  @consolidation_maps << builder.build
end

#content_mappingObject



1044
1045
1046
# File 'lib/lutaml/xml/mapping.rb', line 1044

def content_mapping
  @content_mapping
end

#deep_dupObject



1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
# File 'lib/lutaml/xml/mapping.rb', line 1270

def deep_dup
  self.class.new.tap do |xml_mapping|
    if @root_element
      xml_mapping.root(@root_element.dup, mixed: @mixed_content,
                                          ordered: @ordered)
    end
    if @namespace_class
      xml_mapping.namespace(@namespace_class)
    elsif @namespace_param == :inherit
      xml_mapping.namespace(:inherit)
    elsif @namespace_param == :blank
      xml_mapping.namespace(:blank)
    end

    attributes_to_dup.each do |var_name|
      value = instance_variable_get(var_name)
      # Skip nil values (e.g., @register_elements not yet initialized on fresh copies)
      # Accessor methods will lazily initialize when needed
      next if value.nil?

      xml_mapping.instance_variable_set(var_name, ::Lutaml::Model::Utils.deep_dup(value))
    end
    xml_mapping.instance_variable_set(:@mappings_imported,
                                      ::Hash.new { |h, k| h[k] = false })
    xml_mapping.instance_variable_set(:@register_elements,
                                      ::Hash.new { |h, k| h[k] = {} })
    xml_mapping.instance_variable_set(:@register_attributes,
                                      ::Hash.new { |h, k| h[k] = {} })
    xml_mapping.instance_variable_set(:@register_element_sequences,
                                      ::Hash.new { |h, k| h[k] = [] })
    xml_mapping.instance_variable_set(:@cached_elements, {})
    xml_mapping.instance_variable_set(:@cached_attributes, {})
    xml_mapping.instance_variable_set(:@cached_mappings, {})
    xml_mapping.instance_variable_set(:@finalized, true)
    # CRITICAL: Do NOT copy @mapper_class to the duplicate
    # The duplicate may be used in a different class context
    # and should not carry over the original's mapper_class reference
    xml_mapping.instance_variable_set(:@mapper_class, nil)
  end
end

#documentation(text) ⇒ String

Set documentation text for this mapping

Used for XSD annotation generation.

Parameters:

  • text (String)

    the documentation text

Returns:

  • (String)

    the documentation text



453
454
455
# File 'lib/lutaml/xml/mapping.rb', line 453

def documentation(text)
  @documentation_text = text
end

#dup_mappings(mappings) ⇒ Object



1332
1333
1334
1335
1336
1337
1338
1339
1340
# File 'lib/lutaml/xml/mapping.rb', line 1332

def dup_mappings(mappings)
  new_mappings = {}

  mappings.each do |key, mapping_rule|
    new_mappings[key] = mapping_rule.deep_dup
  end

  new_mappings
end

#element(name) ⇒ String

Set the XML element name for this mapping

This is the primary method for declaring the element name. Use this for the new clean API.

Parameters:

  • name (String)

    the element name

Returns:

  • (String)

    the element name



176
177
178
179
# File 'lib/lutaml/xml/mapping.rb', line 176

def element(name)
  @element_name = name
  @root_element = name # Maintain backward compatibility
end

#elements(register_id = nil) ⇒ Object



1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
# File 'lib/lutaml/xml/mapping.rb', line 1020

def elements(register_id = nil)
  reg_key = register_id || :default
  cached = @cached_elements[reg_key]
  return cached if cached

  result = mapping_elements_hash(register_id).values.flat_map do |v|
    v.is_a?(Array) ? v : [v]
  end
  @cached_elements[reg_key] = result.freeze if @finalized
  result
end

#elements_hashObject

Raw hash access for inheritance and deep_dup operations. Callers may mutate the returned hash (e.g., setting keys).



1236
1237
1238
# File 'lib/lutaml/xml/mapping.rb', line 1236

def elements_hash
  @elements
end

#enable_mixed_contentBoolean Also known as: mixed_content

Enable mixed content for this element

Mixed content means the element can contain both text nodes and child elements interspersed.

Returns:

  • (Boolean)

    true



202
203
204
205
# File 'lib/lutaml/xml/mapping.rb', line 202

def enable_mixed_content
  @mixed_content = true
  @ordered = true # mixed content implies ordered
end

#ensure_mappings_imported!(register_id = nil) ⇒ Object



1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
# File 'lib/lutaml/xml/mapping.rb', line 1067

def ensure_mappings_imported!(register_id = nil)
  # CRITICAL: Return immediately if already imported to prevent redundant processing
  # This prevents the exponential explosion of recursive ensure_imports! calls
  # in complex schemas with hundreds of interdependent classes
  register_id ||= Lutaml::Model::Config.default_register

  # Use per-register tracking
  imported_flag = register_id || :default
  return if @mappings_imported[imported_flag]

  # CRITICAL: Prevent re-entrant calls during import processing
  # This prevents infinite loops when importing models that themselves have imports
  # Architecture: Import resolution should be atomic and non-recursive
  return if @importing_mappings

  # Check if there's any work to do - either regular imports OR sequence imports
  return if importable_mappings.empty? && sequence_importable_mappings.empty?

  # Mark as currently importing to prevent re-entrance
  @importing_mappings = true

  # Track if all imports were successfully resolved
  all_resolved = true

  # Process each deferred mapping import
  importable_mappings.dup.each do |model_sym|
    begin
      model_class = Lutaml::Model::GlobalContext.resolve_type(model_sym,
                                                              register_id)
    rescue Lutaml::Model::UnknownTypeError
      # Model not registered yet - skip for now, will retry later
      all_resolved = false
      next
    end

    next if model_class.nil? # Skip if not registered yet

    # Recursively ensure the imported model's imports are resolved
    # Use the child class's own register if it has one
    if model_class.is_a?(Class) && model_class.include?(Lutaml::Model::Serialize)
      child_register = Lutaml::Model::Register.resolve_for_child(
        model_class, register_id
      )
      model_class.ensure_imports!(child_register)
    end

    # Now import the mappings
    import_model_mappings(model_class, register_id)
  end

  # CRITICAL FIX: Process sequence importable mappings
  # Sequence blocks can have their own deferred imports via import_model_mappings
  # These need to be resolved separately because they add attributes to sequences
  unless sequence_importable_mappings.empty?
    sequence_importable_mappings.each do |sequence, model_syms|
      model_syms.dup.each do |model_sym|
        begin
          model_class = Lutaml::Model::GlobalContext.resolve_type(
            model_sym, register_id
          )
        rescue Lutaml::Model::UnknownTypeError
          # Model not registered yet - skip for now
          all_resolved = false
          next
        end

        next if model_class.nil?

        # Recursively ensure the imported model's imports are resolved
        # Use the child class's own register if it has one
        if model_class.is_a?(Class) && model_class.include?(Lutaml::Model::Serialize)
          child_register = Lutaml::Model::Register.resolve_for_child(
            model_class, register_id
          )
          model_class.ensure_imports!(child_register)
        end

        # Now import into the sequence
        # This will call Sequence#import_model_mappings which adds to sequence.attributes
        # and also calls @model.import_model_mappings to add to main mapping
        sequence.import_model_mappings(model_class, register_id)

        # Remove from queue after successful import
        model_syms.delete(model_sym)
      end
    end

    # Clean up empty sequence entries
    sequence_importable_mappings.reject! { |_, models| models.empty? }
  end

  # Mark as fully imported only if both queues are empty
  @mappings_imported[imported_flag] =
    all_resolved && importable_mappings.empty? && sequence_importable_mappings.empty?
ensure
  # CRITICAL: Always reset the importing flag to prevent deadlock
  # Even if an exception occurs, we must allow future import attempts
  @importing_mappings = false
end

#finalize(mapper_class) ⇒ Object



90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
# File 'lib/lutaml/xml/mapping.rb', line 90

def finalize(mapper_class)
  # Store mapper class for later use in deferred imports
  @mapper_class = mapper_class

  # DO NOT auto-generate root element
  # Models should explicitly declare root in their xml block if needed
  # Type-only models (used as nested types) don't need a root element

  # Resolve any deferred mapping imports before finalizing
  ensure_mappings_imported!

  # Validate mixed content requires collection attribute for content mapping
  validate_mixed_content_collection!(mapper_class)

  # Performance: Clear caches and mark finalized
  @cached_elements.clear
  @cached_attributes.clear
  @cached_mappings.clear
  @finalized = true
end

#finalized?Boolean

Returns:

  • (Boolean)


111
112
113
# File 'lib/lutaml/xml/mapping.rb', line 111

def finalized?
  @finalized
end

#find_attribute(name) ⇒ MappingRule?

Find attribute mapping rule by attribute name

Parameters:

  • name (Symbol, String)

    the attribute name

Returns:



1183
1184
1185
# File 'lib/lutaml/xml/mapping.rb', line 1183

def find_attribute(name)
  attributes.detect { |rule| name == rule.to }
end

#find_by_name(name, type: "Text", node_type: nil, namespace_uri: nil) ⇒ Object



1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
# File 'lib/lutaml/xml/mapping.rb', line 1187

def find_by_name(name, type: "Text", node_type: nil, namespace_uri: nil)
  # If node_type is provided, use it for type detection (preferred)
  if node_type && %i[text cdata].include?(node_type)
    content_mapping
  # Backward compatibility: still check name for old code that doesn't pass node_type
  elsif ["text", "#cdata-section"].include?(name.to_s) && type == "Text"
    content_mapping
  else
    candidates = mappings.select do |rule|
      rule.name == name.to_s || rule.name == name.to_sym
    end
    return candidates.first if namespace_uri.nil? || candidates.one?

    candidates.find do |r|
      r.namespace_class&.uri == namespace_uri
    end || candidates.first
  end
end

#find_by_to(to) ⇒ Object



1206
1207
1208
# File 'lib/lutaml/xml/mapping.rb', line 1206

def find_by_to(to)
  mappings.detect { |rule| rule.to.to_s == to.to_s }
end

#find_by_to!(to) ⇒ Object



1210
1211
1212
1213
1214
1215
1216
# File 'lib/lutaml/xml/mapping.rb', line 1210

def find_by_to!(to)
  mapping = find_by_to(to)

  return mapping if !!mapping

  raise Lutaml::Model::NoMappingFoundError.new(to.to_s)
end

#find_element(name, register_id = nil) ⇒ MappingRule?

Find element mapping rule by attribute name

Parameters:

  • name (Symbol, String)

    the attribute name

Returns:



1175
1176
1177
# File 'lib/lutaml/xml/mapping.rb', line 1175

def find_element(name, register_id = nil)
  elements(register_id).detect { |rule| name == rule.to }
end

#import_model_mappings(model, register_id = nil) ⇒ Object

Import mappings from another model. For default register: imports BOTH attributes (into @mapper_class) AND mappings. For non-default register: stores mappings in register-specific storage (@register_elements, @register_attributes).

Parameters:

  • model (Class)

    The model to import from

  • register_id (Symbol, nil) (defaults to: nil)

    The register context

Raises:



824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
# File 'lib/lutaml/xml/mapping.rb', line 824

def import_model_mappings(model, register_id = nil)
  register_id ||= Lutaml::Model::Config.default_register
  reg_id = register_id
  return import_mappings_later(model, reg_id) if model_importable?(model)
  raise Lutaml::Model::ImportModelWithRootError.new(model) if model.root?(reg_id)

  if register_id != :default
    register_only_import_model_mappings(model, register_id)
    return
  end

  # CRITICAL: Access raw mapping structure directly without triggering import resolution
  # Calling model.mappings_for() can trigger ensure_imports! on that model
  # which creates circular chains: A imports B, B's mappings_for imports C, C imports A
  # Architecture: Access data structure directly, don't call methods that trigger resolutions
  mappings = model.instance_variable_get(:@mappings)&.dig(:xml)
  return unless mappings # Skip if no XML mappings defined

  # ATOMIC IMPORT: Both object model (attributes) AND serialization mappings
  # This mimics XSD complexType composition where importing a type means
  # getting both its structure (attributes) and serialization rules (mappings)

  # 1. Import object model (attributes with accessors)
  #    This defines the data structure of the model
  # CRITICAL: Access attributes directly to avoid triggering ensure_imports!
  imported_attributes = ::Lutaml::Model::Utils.deep_dup(model.instance_variable_get(:@attributes)&.values || [])
  if @mapper_class
    imported_attributes.each do |attr|
      # CRITICAL: Check LOCAL set to avoid calling @mapper_class.attributes()
      # which can trigger ensure_imports! and create circular calls
      unless @attributes_with_methods_defined.include?(attr.name)
        # Define accessor methods on the model class
        @mapper_class.define_attribute_methods(attr, reg_id)
        @attributes_with_methods_defined.add(attr.name)
      end
    end
    # Merge attributes data - use direct access to avoid triggering imports
    attrs_hash = imported_attributes.to_h { |attr| [attr.name, attr] }
    existing_attrs = @mapper_class.instance_variable_get(:@attributes) || {}
    attrs_hash.each do |name, attr|
      if existing_attrs.key?(name)
        existing_attrs[name].options.merge!(attr.options)
      else
        existing_attrs[name] = attr
      end
    end
    @mapper_class.instance_variable_set(:@attributes, existing_attrs)
  end

  # 2. Import serialization mappings (XML element/attribute names → model attributes)
  #    This defines how the data structure maps to/from XML
  # CRITICAL: Deep-copy mapping rules to prevent shared state
  # When multiple classes import the same model, each must have independent MappingRule instances
  # Otherwise, any state mutation during serialization affects ALL importing classes
  @elements.merge!(dup_mappings(mappings.instance_variable_get(:@elements)))
  @attributes.merge!(dup_mappings(mappings.instance_variable_get(:@attributes)))
  # CRITICAL: Deep-copy sequences to prevent shared state
  # Each importing class must have its own Sequence objects
  imported_sequences = mappings.element_sequence.map do |seq|
    seq.deep_dup(self)
  end
  (@element_sequence << imported_sequences).flatten!
end

#importable_mappingsObject



1063
1064
1065
# File 'lib/lutaml/xml/mapping.rb', line 1063

def importable_mappings
  @importable_mappings ||= []
end

#map_all(to:, render_nil: false, render_default: false, delegate: nil, with: {}, namespace: (namespace_set = false nil), prefix: (prefix_provided = false nil), render_empty: false) ⇒ Object Also known as: map_all_content



715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
# File 'lib/lutaml/xml/mapping.rb', line 715

def map_all(
  to:,
render_nil: false,
render_default: false,
delegate: nil,
with: {},
namespace: (namespace_set = false
            nil),
prefix: (prefix_provided = false
         nil),
render_empty: false
)
  validate!(
    ::Lutaml::Model::Constants::RAW_MAPPING_KEY,
    to,
    with,
    render_nil,
    render_empty,
    type: TYPES[:all_content],
  )

  # Warn if prefix parameter is provided
  if prefix_provided != false
    warn "[DEPRECATED] The prefix parameter on map_all is deprecated. " \
         "Define prefix_default in your XmlNamespace class instead. " \
         "Prefix '#{prefix}' will be ignored."
  end

  # Raise error if namespace parameter is provided
  if namespace_set != false
    raise Lutaml::Model::IncorrectMappingArgumentsError,
          "namespace is not allowed at map_all level. " \
          "Namespaces must be declared on the MODEL CLASS itself using 'namespace' at the xml block level."
  end

  rule = MappingRule.new(
    ::Lutaml::Model::Constants::RAW_MAPPING_KEY,
    to: to,
    render_nil: render_nil,
    render_default: render_default,
    with: with,
    delegate: delegate,
    namespace: namespace,
    default_namespace: namespace_uri,
    namespace_set: namespace_set != false,
  )

  @raw_mapping = rule
end

#map_attribute(name, to: nil, render_nil: false, render_default: false, render_empty: false, with: {}, delegate: nil, polymorphic_map: {}, namespace: (namespace_set = false nil), prefix: (prefix_provided = false nil), transform: {}, value_map: {}, as_list: nil, delimiter: nil, form: nil, documentation: nil, xsd_type: (xsd_type_provided = false nil)) ⇒ Object



579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
# File 'lib/lutaml/xml/mapping.rb', line 579

def map_attribute(
  name,
to: nil,
render_nil: false,
render_default: false,
render_empty: false,
with: {},
delegate: nil,
polymorphic_map: {},
namespace: (namespace_set = false
            nil),
prefix: (prefix_provided = false
         nil),
transform: {},
value_map: {},
as_list: nil,
delimiter: nil,
form: nil,
documentation: nil,
xsd_type: (xsd_type_provided = false
           nil)
)
  validate!(
    name, to, with, render_nil, render_empty, type: TYPES[:attribute]
  )

  # Warn if prefix parameter is provided
  if prefix_provided != false
    warn "[DEPRECATED] The prefix parameter on map_attribute is deprecated. " \
         "Define prefix_default in your XmlNamespace class instead. " \
         "Prefix '#{prefix}' will be ignored."
  end

  # Raise error if xsd_type parameter is provided
  if xsd_type_provided != false
    raise Lutaml::Model::IncorrectMappingArgumentsError,
          "xsd_type is not allowed at mapping level. " \
          "XSD type must be declared in Type::Value classes using the xsd_type directive. " \
          "See docs/migration-guides/xsd-type-migration.adoc"
  end

  # Raise error if namespace parameter is a non-nil value at attribute level
  # This is NOT allowed - namespaces should be declared at model level
  # However, namespace: nil is allowed to explicitly opt out of namespace
  # Note: namespace_set is false when default is used, nil when explicit arg passed
  if namespace_set != false && !namespace.nil?
    raise Lutaml::Model::IncorrectMappingArgumentsError,
          "namespace is not allowed at attribute mapping level. " \
          "Namespaces should be declared on the MODEL CLASS itself using 'namespace' at the xml block level."
  end

  if name == "schemaLocation"
    location = caller_locations(1, 1)[0]
    caller_file = if defined?(File) && File.respond_to?(:basename)
                    File.basename(location.path)
                  else
                    location.path.to_s.split("/").last
                  end
    ::Lutaml::Model::Logger.warn_auto_handling(
      name: name,
      caller_file: caller_file,
      caller_line: location.lineno,
    )
  end

  rule = MappingRule.new(
    name,
    to: to,
    render_nil: render_nil,
    render_default: render_default,
    render_empty: render_empty,
    with: with,
    delegate: delegate,
    namespace: namespace,
    attribute: true,
    polymorphic_map: polymorphic_map,
    default_namespace: namespace_uri,
    namespace_set: namespace_set != false,
    transform: transform,
    value_map: value_map,
    as_list: as_list,
    delimiter: delimiter,
    form: form,
    documentation: documentation,
  )
  # Use eql? to detect and skip exact duplicates (prevents accumulation)
  key = rule.namespaced_name
  existing = @attributes[key]

  if existing.nil?
    # New mapping - store directly
    @attributes[key] = rule
  elsif existing.is_a?(Array)
    # Array exists - check for duplicate or add
    duplicate_index = existing.find_index { |r| r.eql?(rule) }
    # Only add if not a duplicate
    existing << rule unless duplicate_index
  elsif existing.eql?(rule)
    # Exact duplicate - already stored, no action needed
  else
    # Different mapping (polymorphic) - convert to array
    @attributes[key] = [existing, rule]
  end
end

#map_content(to: nil, render_nil: false, render_default: false, render_empty: false, with: {}, delegate: nil, mixed: false, cdata: false, transform: {}, value_map: {}) ⇒ Object



684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
# File 'lib/lutaml/xml/mapping.rb', line 684

def map_content(
  to: nil,
render_nil: false,
render_default: false,
render_empty: false,
with: {},
delegate: nil,
mixed: false,
cdata: false,
transform: {},
value_map: {}
)
  validate!(
    "content", to, with, render_nil, render_empty, type: TYPES[:content]
  )

  @content_mapping = MappingRule.new(
    nil,
    to: to,
    render_nil: render_nil,
    render_default: render_default,
    render_empty: render_empty,
    with: with,
    delegate: delegate,
    mixed_content: mixed,
    cdata: cdata,
    transform: transform,
    value_map: value_map,
  )
end

#map_element(name, to: nil, render_nil: false, render_default: false, render_empty: false, treat_nil: :nil, treat_empty: :empty, treat_omitted: :nil, with: {}, delegate: nil, cdata: false, polymorphic: {}, namespace: (namespace_set = false nil), prefix: (prefix_provided = false nil), transform: {}, value_map: {}, form: nil, documentation: nil, xsd_type: (xsd_type_provided = false nil)) ⇒ Object



482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
# File 'lib/lutaml/xml/mapping.rb', line 482

def map_element(
  name,
to: nil,
render_nil: false,
render_default: false,
render_empty: false,
treat_nil: :nil,
treat_empty: :empty,
treat_omitted: :nil,
with: {},
delegate: nil,
cdata: false,
polymorphic: {},
namespace: (namespace_set = false
            nil),
prefix: (prefix_provided = false
         nil),
transform: {},
value_map: {},
form: nil,
documentation: nil,
xsd_type: (xsd_type_provided = false
           nil)
)
  validate!(
    name, to, with, render_nil, render_empty, type: TYPES[:element]
  )

  # Warn if prefix parameter is provided
  if prefix_provided != false
    warn "[DEPRECATED] The prefix parameter on map_element is deprecated. " \
         "Define prefix_default in your XmlNamespace class instead. " \
         "Prefix '#{prefix}' will be ignored."
  end

  # Raise error if xsd_type parameter is provided
  if xsd_type_provided != false
    raise Lutaml::Model::IncorrectMappingArgumentsError,
          "xsd_type is not allowed at mapping level. " \
          "XSD type must be declared in Type::Value classes using the xsd_type directive. " \
          "See docs/migration-guides/xsd-type-migration.adoc"
  end

  # Raise error if namespace parameter is a non-nil value at element level
  # This is NOT allowed - namespaces should be declared at model level
  # However, namespace: nil is allowed to explicitly opt out of namespace
  # Note: namespace_set is false when default is used, nil when explicit arg passed
  if namespace_set != false && !namespace.nil?
    raise Lutaml::Model::IncorrectMappingArgumentsError,
          "namespace is not allowed at element mapping level. " \
          "Namespaces must be declared on the MODEL CLASS itself using 'namespace' at the xml block level. " \
          "Each model class should declare its own namespace, not individual elements."
  end

  rule = MappingRule.new(
    name,
    to: to,
    render_nil: render_nil,
    render_default: render_default,
    render_empty: render_empty,
    treat_nil: treat_nil,
    treat_empty: treat_empty,
    treat_omitted: treat_omitted,
    with: with,
    delegate: delegate,
    cdata: cdata,
    namespace: namespace,
    default_namespace: namespace_uri,
    polymorphic: polymorphic,
    namespace_set: namespace_set != false || namespace == :inherit,
    transform: transform,
    value_map: value_map,
    form: form,
    documentation: documentation,
  )
  # Store rules with the same element name in an array to support
  # multiple mapping rules for the same element name with different target types
  # Use eql? to detect and skip exact duplicates (prevents accumulation)
  key = rule.namespaced_name
  existing = @elements[key]

  if existing.nil?
    # New mapping - store directly
    @elements[key] = rule
  elsif existing.is_a?(Array)
    # Array exists - check for duplicate or add
    duplicate_index = existing.find_index { |r| r.eql?(rule) }
    # Only add if not a duplicate
    existing << rule unless duplicate_index
  elsif existing.eql?(rule)
    # Exact duplicate - already stored, no action needed
  else
    # Different mapping (polymorphic) - convert to array
    @elements[key] = [existing, rule]
  end
end

#map_instances(to:, polymorphic: {}) ⇒ Object



478
479
480
# File 'lib/lutaml/xml/mapping.rb', line 478

def map_instances(to:, polymorphic: {})
  map_element(to, to: to, polymorphic: polymorphic)
end

#map_processing_instruction(target, to:) ⇒ Object

Map XML processing instructions with a given target to a model attribute.

During serialization, the attribute value (Hash) is expanded into individual PIs: each key-value pair generates ‘<?target key=“value”?>`. During deserialization, PIs with matching target are parsed into the hash.

Examples:

xml do
  root "rfc"
  map_processing_instruction "rfc", to: :pi_settings
end

# With pi_settings = { "strict" => "yes", "compact" => "yes" }
# generates:
# <?rfc strict="yes"?>
# <?rfc compact="yes"?>
# <rfc>...</rfc>

Parameters:

  • target (String)

    the PI target name (e.g., “rfc”)

  • to (Symbol)

    the model attribute name



787
788
789
790
791
# File 'lib/lutaml/xml/mapping.rb', line 787

def map_processing_instruction(target, to:)
  @processing_instruction_mappings << ProcessingInstructionMapping.new(
    target.to_s, to
  )
end

#mapping_attributes_hash(register_id = nil) ⇒ Object



1218
1219
1220
1221
1222
1223
1224
# File 'lib/lutaml/xml/mapping.rb', line 1218

def mapping_attributes_hash(register_id = nil)
  if register_id.nil? || register_id == :default
    @attributes
  else
    @attributes.merge(@register_attributes[register_id])
  end
end

#mapping_elements_hash(register_id = nil) ⇒ Object



1226
1227
1228
1229
1230
1231
1232
# File 'lib/lutaml/xml/mapping.rb', line 1226

def mapping_elements_hash(register_id = nil)
  if register_id.nil? || register_id == :default
    @elements
  else
    @elements.merge(@register_elements[register_id])
  end
end

#mappings(register_id = nil) ⇒ Object



1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
# File 'lib/lutaml/xml/mapping.rb', line 1052

def mappings(register_id = nil)
  reg_key = register_id || :default
  cached = @cached_mappings[reg_key]
  return cached if cached

  result = elements(register_id) + attributes(register_id) + [content_mapping,
                                                              raw_mapping].compact
  @cached_mappings[reg_key] = result.freeze if @finalized
  result
end

#merge_elements_sequence(mapping) ⇒ Object



1264
1265
1266
1267
1268
# File 'lib/lutaml/xml/mapping.rb', line 1264

def merge_elements_sequence(mapping)
  mapping.element_sequence.each do |sequence|
    element_sequence << sequence_dup(sequence)
  end
end

#mixed_content?Boolean

Check if mixed content is enabled

Returns:

  • (Boolean)

    true if mixed content is enabled



159
160
161
# File 'lib/lutaml/xml/mapping.rb', line 159

def mixed_content?
  @mixed_content || false
end

#namespace(ns_class_or_symbol, _deprecated_prefix = nil) ⇒ void

This method returns an undefined value.

Set the XML namespace for this mapping

Examples:

Using XmlNamespace class (REQUIRED)

namespace ContactNamespace

Using :inherit to inherit parent namespace

namespace :inherit

Using :blank for explicit no namespace

namespace :blank

Parameters:

  • ns_class_or_symbol (Class, Symbol)

    XmlNamespace class or :blank/:inherit

  • _deprecated_prefix (String, nil) (defaults to: nil)

    DEPRECATED - no longer used

Raises:



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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
# File 'lib/lutaml/xml/mapping.rb', line 345

def namespace(ns_class_or_symbol, _deprecated_prefix = nil)
  # Only raise error for explicitly marked no_root (using deprecated method)
  # Type-only models (no element declared) CAN have namespaces
  raise Lutaml::Model::NoRootNamespaceError if @no_root

  # Warn if prefix parameter is provided
  if _deprecated_prefix
    warn "[DEPRECATED] The prefix parameter on namespace() is deprecated. " \
         "Define prefix_default in your XmlNamespace class instead. " \
         "Prefix '#{_deprecated_prefix}' will be ignored."
  end

  # Handle :blank symbol - explicit blank namespace
  if ns_class_or_symbol == :blank
    @namespace_class = nil
    @namespace_uri = nil
    @namespace_prefix = nil
    @namespace_set = true # Mark as explicitly set
    @namespace_param = :blank # Store original value
    return
  end

  # Handle :inherit symbol
  if ns_class_or_symbol == :inherit
    @namespace_set = true
    @namespace_param = :inherit
    return
  end

  # nil means "not set" - DON'T set @namespace_set
  if ns_class_or_symbol.nil?
    @namespace_class = nil
    @namespace_uri = nil
    @namespace_prefix = nil
    @namespace_set = false # Explicitly NOT set
    @namespace_param = nil
    return
  end

  # Accept both Lutaml::Xml::Namespace and Lutaml::Model::Xml::Namespace for compatibility
  is_namespace_class = ns_class_or_symbol.is_a?(Class) && (
    (defined?(::Lutaml::Xml::Namespace) && ns_class_or_symbol < ::Lutaml::Xml::Namespace) ||
    (defined?(::Lutaml::Model::Xml::Namespace) && ns_class_or_symbol < ::Lutaml::Model::Xml::Namespace)
  )

  if is_namespace_class
    # XmlNamespace class passed - register and use
    @namespace_class = NamespaceClassRegistry.instance.register_named(ns_class_or_symbol)
    @namespace_uri = ns_class_or_symbol.uri
    @namespace_prefix = ns_class_or_symbol.prefix_default
  elsif ns_class_or_symbol.is_a?(String)
    # String URI - NOT SUPPORTED
    raise Lutaml::Xml::Error::InvalidNamespaceError.new(
      expected: "XmlNamespace class",
      got: ns_class_or_symbol,
      message: "String namespace URIs are not supported. " \
               "Define an XmlNamespace class instead. " \
               "See docs/_guides/xml-namespaces.adoc for migration guide.",
    )
  else
    raise Lutaml::Xml::Error::InvalidNamespaceError.new(
      expected: "XmlNamespace class, :inherit, or :blank",
      got: ns_class_or_symbol,
    )
  end
end

#namespace_class?Boolean

Whether namespace_class was explicitly set (not nil)

Returns:

  • (Boolean)


1245
1246
1247
# File 'lib/lutaml/xml/mapping.rb', line 1245

def namespace_class?
  !@namespace_class.nil?
end

#namespace_set?Boolean

Whether namespace was explicitly set via DSL

Returns:

  • (Boolean)


1250
1251
1252
# File 'lib/lutaml/xml/mapping.rb', line 1250

def namespace_set?
  !!@namespace_set
end

#no_element?Boolean

Check if this mapping has no element declaration

Returns:

  • (Boolean)

    true if no element is declared



316
317
318
# File 'lib/lutaml/xml/mapping.rb', line 316

def no_element?
  !element_name
end

#no_rootObject

Deprecated.

Use absence of element() declaration and type_name() instead

Mark this model as having no root element (type-only)



295
296
297
298
299
300
# File 'lib/lutaml/xml/mapping.rb', line 295

def no_root
  warn "[Lutaml::Model] DEPRECATED: no_root is deprecated. " \
       "Simply omit the element declaration for type-only models. " \
       "Use type_name() to set the XSD type name."
  @no_root = true
end

#no_root?Boolean

Check if this mapping has no root element

Returns true if:

  • The deprecated @no_root flag is explicitly set, OR

  • No element is declared (modern pattern - just omit element() call)

Returns:

  • (Boolean)

    true if no root element



309
310
311
# File 'lib/lutaml/xml/mapping.rb', line 309

def no_root?
  !!@no_root || no_element?
end

#on_attribute(name, id: nil, &block) ⇒ void

This method returns an undefined value.

Add a complex listener for an XML attribute with a custom handler block.

Examples:

class MyMapping < Lutaml::Xml::Mapping
  on_attribute "xmlAttr", id: :parse_attr do |element, context|
    context[:custom] = element["xmlAttr"]
  end
end

Parameters:

  • name (String)

    XML attribute name

  • id (Symbol, String, nil) (defaults to: nil)

    Unique identifier for override/omit.

  • block (Proc)

    Custom handler receiving (element, context)



1394
1395
1396
1397
1398
1399
1400
# File 'lib/lutaml/xml/mapping.rb', line 1394

def on_attribute(name, id: nil, &block)
  add_listener(Lutaml::Xml::Listener.new(
                 target: name,
                 id: id,
                 handler: block,
               ))
end

#on_element(name, id: nil, &block) ⇒ void

This method returns an undefined value.

Add a complex listener for an XML element with a custom handler block.

Unlike map_element which creates a simple listener (framework handles deserialization), on_element allows custom deserialization logic.

Multiple listeners for the same element are allowed — all matching listeners are invoked during parsing.

Examples:

Custom deserialization

class MyMapping < Lutaml::Xml::Mapping
  on_element "CustomElement", id: :custom_parse do |element, context|
    context[:custom] = CustomParser.parse(element)
  end
end

Multiple listeners for same element

class MyMapping < Lutaml::Xml::Mapping
  on_element "Documentation", id: :parse_docs do |element, context|
    context[:documentation] = Documentation.from_xml(element)
  end

  on_element "Documentation", id: :log_docs do |element, context|
    logger.info("Parsing docs: #{element.text}")
  end
end

Parameters:

  • name (String)

    XML element name

  • id (Symbol, String, nil) (defaults to: nil)

    Unique identifier for override/omit. If omitted, listener cannot be targeted by omit_listener.

  • block (Proc)

    Custom handler receiving (element, context)



1373
1374
1375
1376
1377
1378
1379
# File 'lib/lutaml/xml/mapping.rb', line 1373

def on_element(name, id: nil, &block)
  add_listener(Lutaml::Xml::Listener.new(
                 target: name,
                 id: id,
                 handler: block,
               ))
end

#orderedBoolean

Enable ordered content for this element

Ordered content means element order is preserved during round-trip serialization without validation. This is different from ‘sequence` which enforces and validates order.

Use this when:

  • Element order matters for your application

  • You need to preserve input order exactly

  • You DON’T want to validate/enforce specific order

Use ‘sequence` when you need strict order validation.

Returns:

  • (Boolean)

    true



284
285
286
# File 'lib/lutaml/xml/mapping.rb', line 284

def ordered
  @ordered = true
end

#ordered?Boolean?

Return whether this mapping uses ordered content

Returns:

  • (Boolean, nil)

    true if ordered, nil if not set



165
166
167
# File 'lib/lutaml/xml/mapping.rb', line 165

def ordered?
  @ordered
end

#polymorphic_mappingObject



1311
1312
1313
# File 'lib/lutaml/xml/mapping.rb', line 1311

def polymorphic_mapping
  mappings.find(&:polymorphic_mapping?)
end

#prefixed_rootObject



320
321
322
323
324
325
326
# File 'lib/lutaml/xml/mapping.rb', line 320

def prefixed_root
  if namespace_uri && namespace_prefix
    "#{namespace_prefix}:#{root_element}"
  else
    root_element
  end
end

#preserve_whitespace?Boolean

Whether this mapping should auto-add xml:space=“preserve”

Returns:

  • (Boolean)


240
241
242
# File 'lib/lutaml/xml/mapping.rb', line 240

def preserve_whitespace?
  @xml_space == :preserve
end

#raw_mappingObject



1048
1049
1050
# File 'lib/lutaml/xml/mapping.rb', line 1048

def raw_mapping
  @raw_mapping
end

#root(name, mixed: false, ordered: false) ⇒ String

Set the root element name with optional configuration

This is kept as an alias to element() for backward compatibility, but also supports the mixed: and ordered: options.

Parameters:

  • name (String)

    the root element name

  • mixed (Boolean) (defaults to: false)

    whether content is mixed (text + elements)

  • ordered (Boolean) (defaults to: false)

    whether to preserve element order

Returns:

  • (String)

    the root element name



190
191
192
193
194
# File 'lib/lutaml/xml/mapping.rb', line 190

def root(name, mixed: false, ordered: false)
  element(name)
  @mixed_content = mixed
  @ordered = ordered || mixed # mixed content is always ordered
end

#root?Boolean

Returns:

  • (Boolean)


288
289
290
# File 'lib/lutaml/xml/mapping.rb', line 288

def root?
  !!root_element
end

#sequence(&block) ⇒ Object



793
794
795
796
797
798
# File 'lib/lutaml/xml/mapping.rb', line 793

def sequence(&block)
  @element_sequence << ::Lutaml::Model::Sequence.new(self,
                                                     format: :xml).tap do |s|
    s.instance_eval(&block)
  end
end

#sequence_dup(sequence) ⇒ Object



1256
1257
1258
1259
1260
1261
1262
# File 'lib/lutaml/xml/mapping.rb', line 1256

def sequence_dup(sequence)
  Lutaml::Model::Sequence.new(self, format: :xml).tap do |instance|
    sequence.attributes.each do |attr|
      instance.attributes << attr.deep_dup
    end
  end
end

#sequence_importable_mappingsObject



1167
1168
1169
# File 'lib/lutaml/xml/mapping.rb', line 1167

def sequence_importable_mappings
  @sequence_importable_mappings ||= ::Hash.new { |h, k| h[k] = [] }
end

#set_mappings_imported(value) ⇒ Object



905
906
907
908
909
910
911
# File 'lib/lutaml/xml/mapping.rb', line 905

def set_mappings_imported(value)
  if @mappings_imported.is_a?(Hash)
    @mappings_imported.each_key { |k| @mappings_imported[k] = value }
  else
    @mappings_imported = value
  end
end

#type_name(name = nil) ⇒ String? Also known as: xsd_type

Set explicit type name for XSD generation

By default, type name is inferred as “ClassNameType”. Use this to override.

Parameters:

  • name (String, nil) (defaults to: nil)

    the type name

Returns:

  • (String, nil)

    the type name



464
465
466
467
# File 'lib/lutaml/xml/mapping.rb', line 464

def type_name(name = nil)
  @type_name_value = name if name
  @type_name_value
end

#validate!(key, to, with, render_nil, render_empty, type: nil) ⇒ Object



913
914
915
916
917
918
919
920
921
922
923
# File 'lib/lutaml/xml/mapping.rb', line 913

def validate!(key, to, with, render_nil, render_empty, type: nil)
  validate_raw_mappings!(type)
  validate_to_and_with_arguments!(key, to, with)

  if render_nil == :as_empty || render_empty == :as_empty
    raise ::Lutaml::Model::IncorrectMappingArgumentsError.new(
      ":as_empty is not supported for XML mappings. " \
      "Use :as_blank instead to create blank XML elements.",
    )
  end
end

#validate_mixed_content_collection!(mapper_class) ⇒ Object

Validate that mixed content models have a collection attribute for their content mapping. When mixed_content is enabled, the XML element can contain interleaved text and child elements, resulting in multiple text nodes. The content attribute must be a string collection to hold all of them; otherwise only the first text node is preserved.



120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
# File 'lib/lutaml/xml/mapping.rb', line 120

def validate_mixed_content_collection!(mapper_class)
  return unless @mixed_content && @content_mapping

  attr_name = @content_mapping.to
  return unless attr_name

  # Follow delegate chain to find the actual attribute definition
  delegate = @content_mapping.delegate
  attr_def = if delegate
               delegate_obj = mapper_class.attributes[delegate]
               delegate_obj&.type&.attributes&.dig(attr_name) if delegate_obj&.type.respond_to?(:attributes)
             else
               mapper_class.attributes[attr_name]
             end
  return unless attr_def
  return if attr_def.collection?

  raise Lutaml::Model::MixedContentCollectionError.new(attr_name,
                                                       mapper_class)
end

#validate_namespace_prefix!(prefix) ⇒ void

This method returns an undefined value.

Validate namespace prefix parameter

Raises ArgumentError if prefix is Hash or Array, which indicates the common mistake of passing options as prefix.

Parameters:

  • prefix (Object)

    the prefix parameter to validate

Raises:

  • (ArgumentError)

    if prefix is Hash or Array



965
966
967
968
969
970
971
# File 'lib/lutaml/xml/mapping.rb', line 965

def validate_namespace_prefix!(prefix)
  if prefix.is_a?(Hash) || prefix.is_a?(Array)
    raise ArgumentError,
          "namespace prefix must be a String or Symbol, not #{prefix.class}. " \
          "Did you mean to use 'root' with mixed: true?"
  end
end

#validate_namespace_scope!(namespaces) ⇒ void

This method returns an undefined value.

Validate namespace_scope parameter

Ensures all items are XmlNamespace classes or valid Hash entries

Parameters:

  • namespaces (Array)

    the namespaces to validate

Raises:

  • (ArgumentError)

    if invalid namespace classes provided



980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
# File 'lib/lutaml/xml/mapping.rb', line 980

def validate_namespace_scope!(namespaces)
  unless namespaces.is_a?(Array)
    raise ArgumentError,
          "namespace_scope must be an Array of XmlNamespace classes, " \
          "got #{namespaces.class}"
  end

  namespaces.each do |ns|
    if ns.is_a?(Class)
      unless ns < Lutaml::Xml::Namespace
        raise ArgumentError,
              "namespace_scope must contain only XmlNamespace classes, " \
              "got #{ns}"
      end
    elsif ns.is_a?(::Hash)
      ns_class = ns[:namespace]
      unless ns_class.is_a?(Class) && ns_class < Lutaml::Xml::Namespace
        raise ArgumentError,
              "namespace_scope Hash entry must have :namespace key " \
              "with XmlNamespace class, got #{ns_class.class}"
      end

      # Validate :declare option if present
      if ns.key?(:declare)
        declare_value = ns[:declare]
        valid_modes = %i[auto always never]
        unless valid_modes.include?(declare_value)
          raise ArgumentError,
                "namespace_scope Hash entry :declare must be one of " \
                "#{valid_modes.inspect}, got #{declare_value.inspect}"
        end
      end
    else
      raise ArgumentError,
            "namespace_scope must contain only XmlNamespace classes or Hashes, " \
            "got #{ns.class}"
    end
  end
end

#validate_raw_mappings!(type) ⇒ Object



945
946
947
948
949
950
951
952
953
954
955
# File 'lib/lutaml/xml/mapping.rb', line 945

def validate_raw_mappings!(type)
  if !@raw_mapping.nil? && type != TYPES[:attribute]
    raise StandardError, "#{type} is not allowed, only #{TYPES[:attribute]} " \
                         "is allowed with #{TYPES[:all_content]}"
  end

  if !(elements.empty? && content_mapping.nil?) && type == TYPES[:all_content]
    raise StandardError,
          "#{TYPES[:all_content]} is not allowed with other mappings"
  end
end

#validate_to_and_with_arguments!(key, to, with) ⇒ Object



925
926
927
928
929
930
931
932
933
# File 'lib/lutaml/xml/mapping.rb', line 925

def validate_to_and_with_arguments!(key, to, with)
  if to.nil? && with.empty?
    raise ::Lutaml::Model::IncorrectMappingArgumentsError.new(
      ":to or :with argument is required for mapping '#{key}'",
    )
  end

  validate_with_options!(key, to, with)
end

#validate_with_options!(key, to, with) ⇒ Object



935
936
937
938
939
940
941
942
943
# File 'lib/lutaml/xml/mapping.rb', line 935

def validate_with_options!(key, to, with)
  return true if to

  if !with.empty? && (with[:from].nil? || with[:to].nil?)
    raise ::Lutaml::Model::IncorrectMappingArgumentsError.new(
      ":with argument for mapping '#{key}' requires :to and :from keys",
    )
  end
end

#w3c_attributes(*attrs) ⇒ Object

Convenience method for standard W3C XML attributes

Automatically creates attribute mappings for attributes that use W3C types. The attribute must already be declared with a W3C type.

Available options: :lang, :space, :base, :id

Examples:

class Paragraph < Lutaml::Model::Serializable
  attribute :lang, Lutaml::Xml::W3c::XmlLangType
  attribute :space, Lutaml::Xml::W3c::XmlSpaceType
  attribute :content, :string

  xml do
    element "p"
    w3c_attributes :lang, :space  # Maps to xml:lang and xml:space
    map_content to: :content
  end
end

Parameters:

  • attrs (Array<Symbol>)

    List of W3C attribute names to auto-map



264
265
266
267
268
# File 'lib/lutaml/xml/mapping.rb', line 264

def w3c_attributes(*attrs)
  attrs.each do |attr|
    map_attribute attr.to_s, to: attr
  end
end