Class: Lutaml::Model::Attribute

Inherits:
Object
  • Object
show all
Includes:
CollectionHandler, DeepDupable, RestrictionValidation
Defined in:
lib/lutaml/model/attribute.rb

Constant Summary collapse

TO_FORMAT_METHODS =

Symbol interpolation (:"to_#format") allocates a String and a Symbol per call on the serialization hot path; the table serves the known formats and the fallback keeps exotic ones working.

{
  xml: :to_xml,
  json: :to_json,
  yaml: :to_yaml,
  toml: :to_toml,
  hash: :to_hash,
}.freeze
ALLOWED_OPTIONS =
%i[
  raw
  default
  delegate
  collection
  values
  pattern
  transform
  choice
  sequence
  method
  method_name
  polymorphic
  polymorphic_class
  initialize_empty
  validations
  required
  ref_model_class
  ref_key_attribute
  xsd_type
  union_member_types
  min
  max
  signed
  min_length
  max_length
].freeze
TypeProbeCache =

Per-type-class memo of the custom from_xml/from_json probe used by #cast. Isolated cache holder: enclosing-class freezes (some suites freeze Lutaml::Model::Attribute) would freeze a constant Hash with it.

::Class.new do
  class << self
    def cache
      @cache ||= {}
    end
  end
end
MODEL_STRINGS =
[
  Lutaml::Model::Type::String,
  "String",
  :string,
].freeze
CHILD_PROPAGATION_KEYS =

Delegate propagation to DeserializationContext for single source of truth.

Serialize::DeserializationContext::PROPAGATION_KEYS
WARN_ON_OVERRIDE =

Methods where accidental override is likely to cause issues All names are allowed - this list only controls which ones get a warning Format-specific serialization methods (to_xml, to_json, etc.) are pushed by each format plugin at load time via format_specific_warn_names.

%i[
  # Ruby core - overriding breaks fundamental behavior
  hash object_id class send method

  # Object lifecycle - overriding without super breaks things
  initialize

  # Serialization methods - overriding breaks serialization
  to_format

  # Internal helpers - overriding breaks internal logic
  attr_value attribute_exist? key_exist? key_value
  using_default? using_default_for value_set_for
  method_missing respond_to_missing?
].freeze
EMPTY_TRANSFORM_HASH =

Performance: Frozen empty hash to reduce allocations

{}.freeze
EMPTY_VALUES_ARRAY =

Performance: Frozen empty array to reduce allocations

[].freeze

Constants included from CollectionHandler

CollectionHandler::KEYWORD_PARAM_KINDS

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from RestrictionValidation

#effective_restriction_facets, #validate_restriction_configuration!, #validate_restriction_values!

Methods included from CollectionHandler

#build_collection, #coerce_to_collection?, #collection, #collection?, #collection_class, #collection_instance?, #custom_collection?, #initialize_accepts_register?, #min_collection_zero?, #resolved_collection, #singular?

Constructor Details

#initialize(name, type, options = {}) ⇒ Attribute

Returns a new instance of Attribute.



139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
# File 'lib/lutaml/model/attribute.rb', line 139

def initialize(name, type, options = {})
  skip_validation = options.fetch(:skip_validation, false)

  unless skip_validation
    validate_name!(
      name, reserved_methods: Lutaml::Model::Serializable.instance_methods
    )
  end

  @name = name
  @options = options.except(:skip_validation)

  validate_presence!(type) unless skip_validation
  @type = type
  @unresolved_type = type
  process_options! unless skip_validation
end

Instance Attribute Details

#name ⇒ Object (readonly)

Returns the value of attribute name.



6
7
8
# File 'lib/lutaml/model/attribute.rb', line 6

def name
  @name
end

#options ⇒ Object (readonly)

Returns the value of attribute options.



6
7
8
# File 'lib/lutaml/model/attribute.rb', line 6

def options
  @options
end

#validations ⇒ Object



381
382
383
# File 'lib/lutaml/model/attribute.rb', line 381

def validations
  @options[:validations]
end

Class Method Details

.cast_from_string!(type) ⇒ Object



133
134
135
136
137
# File 'lib/lutaml/model/attribute.rb', line 133

def self.cast_from_string!(type)
  Type.const_get(type)
rescue NameError
  raise ArgumentError, "Unknown Lutaml::Model::Type: #{type}"
end

.cast_from_symbol!(type) ⇒ Object



127
128
129
130
131
# File 'lib/lutaml/model/attribute.rb', line 127

def self.cast_from_symbol!(type)
  Type.lookup(type)
rescue UnknownTypeError
  raise ArgumentError, "Unknown Lutaml::Model::Type: #{type}"
end

.cast_type!(type) ⇒ Object



117
118
119
120
121
122
123
124
125
# File 'lib/lutaml/model/attribute.rb', line 117

def self.cast_type!(type)
  case type
  when Symbol then cast_from_symbol!(type)
  when String then cast_from_string!(type)
  when Class then type
  else
    raise ArgumentError, "Unknown Lutaml::Model::Type: #{type}"
  end
end

.custom_from_probe?(type) ⇒ Boolean

Public reader for compiled rule plans: does this type class carry a custom from_xml/from_json (answer static, probed once)?

Returns:

  • (Boolean)


65
66
67
68
69
70
71
72
73
# File 'lib/lutaml/model/attribute.rb', line 65

def custom_from_probe?(type)
  cache = TypeProbeCache.cache
  return cache[type] if cache.key?(type)

  base = Lutaml::Model::Type::Value.singleton_class
  cache[type] =
    type.method(:from_xml).owner != base ||
    type.method(:from_json).owner != base
end

.default_evaluation? ⇒ Boolean

Returns:

  • (Boolean)


632
633
634
# File 'lib/lutaml/model/attribute.rb', line 632

def self.default_evaluation?
  Thread.current[:__lutaml_evaluating_default] == true
end

.evaluating_default ⇒ Object

Marks the dynamic extent in which a default proc runs against a model instance, so Serialize#method_missing can fall back to the model class for methods the instance does not define (0.7.x compatibility, lutaml-model#745).



624
625
626
627
628
629
630
# File 'lib/lutaml/model/attribute.rb', line 624

def self.evaluating_default
  previous = Thread.current[:__lutaml_evaluating_default]
  Thread.current[:__lutaml_evaluating_default] = true
  yield
ensure
  Thread.current[:__lutaml_evaluating_default] = previous
end

.format_specific_warn_names ⇒ Object



109
110
111
# File 'lib/lutaml/model/attribute.rb', line 109

def self.format_specific_warn_names
  @format_specific_warn_names
end

.warn_on_override_names ⇒ Object



113
114
115
# File 'lib/lutaml/model/attribute.rb', line 113

def self.warn_on_override_names
  WARN_ON_OVERRIDE + @format_specific_warn_names
end

Instance Method Details

#_default_kind ⇒ Object



612
613
614
615
616
617
618
# File 'lib/lutaml/model/attribute.rb', line 612

def _default_kind
  return :delegate if delegate
  return :proc if options[:default].is_a?(Proc)
  return :static if options.key?(:default)

  :none
end

#apply_value_map(value, value_map) ⇒ Object

Apply a value map to transform a value.

value_map keys (:nil, :empty, :omitted) each map either to a symbolic option (:nil, :empty, :omitted) or, for Boolean attributes, directly to true/false. The nested form value_map[key] = true/false is accepted unconditionally; the bare form value_map = true/false is gated on the attribute being a Boolean type.



450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
# File 'lib/lutaml/model/attribute.rb', line 450

def apply_value_map(value, value_map)
  key = if value.nil? then :nil
        elsif Utils.empty?(value) then :empty
        elsif Utils.uninitialized?(value) then :omitted
        end
  return value unless key

  nested = value_map.dig(:from, key)
  return nested if nested.is_a?(TrueClass) || nested.is_a?(FalseClass)

  option = value_map[key]
  if (option.is_a?(TrueClass) || option.is_a?(FalseClass)) &&
      value_map_boolean?
    return option
  end

  case option
  when :nil
    nil
  when :empty
    if key == :empty then value
    elsif collection? then build_collection
    else ""
    end
  else
    Lutaml::Model::UninitializedClass.instance
  end
end

#cast(value, format, register, options = {}) ⇒ Object



880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
# File 'lib/lutaml/model/attribute.rb', line 880

def cast(value, format, register, options = {})
  # Sentinel: never a cast input. nil flows on — absent values
  # reach the type's cast (ST_OnOff booleans, #795); a cast that
  # manufactures a typed instance from nothing is the phantom
  # #793 removed, suppressed here as in cast_element.
  return value if Utils.uninitialized?(value)

  if value.nil?
    result = cast_present(value, format, register, options)
    return result if result.nil?
    return nil if result.is_a?(Lutaml::Model::Type::Value) ||
      result.is_a?(Lutaml::Model::Serialize)

    return result
  end

  cast_present(value, format, register, options)
end

#cast_derived(value, register) ⇒ Object

Cast the value a derived reader just recomputed.

A derived attribute has no ivar and no writer. Its reader runs the source method and casts the result on every call, which makes the reader a casting entry point of its own — nothing a writer-side guard can reach. A collection still has to come back as a collection here, even when the source method returned nothing.

Parameters:

  • value (Object) —

    whatever the source method returned

  • register (Symbol) —

    register for type resolution

Returns:

  • (Object) —

    the cast value, or an empty collection



428
429
430
431
432
433
434
435
436
437
438
439
440
441
# File 'lib/lutaml/model/attribute.rb', line 428

def cast_derived(value, register)
  return cast_element(value, register) unless collection?
  return build_collection if no_data?(value)
  return cast_value(value, register) if collection_instance?(value)
  # A plain Array is a list of source elements even when the attribute
  # declares its own collection class, which collection_instance? only
  # recognises by that class. Without this it becomes one element whose
  # value is the inspected Array.
  if value.is_a?(::Array)
    return build_collection(value.map { |v| cast_element(v, register) })
  end

  build_collection(cast_element(value, register))
end

#cast_element(value, register) ⇒ Object



499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
# File 'lib/lutaml/model/attribute.rb', line 499

def cast_element(value, register)
  # Resolve first: an undeclared type has to raise UnknownTypeError
  # even for a nil value (the 0.8.33 behavior).
  resolved_type = type(register)

  return value if Utils.uninitialized?(value)

  # nil reaches the type's cast — the long-shipped contract
  # ST_OnOff-style types depend on (absent attribute -> cast(nil)
  # -> false; lutaml-model#795). What nil must NOT do is
  # manufacture a typed INSTANCE from nothing: that is the
  # phantom #793 removed, suppressed by the post-check below.
  if value.nil?
    result = cast_element_present(value, register, resolved_type)
    return result if result.nil?
    return nil if result.is_a?(Lutaml::Model::Type::Value) ||
      result.is_a?(Lutaml::Model::Serialize)

    return result
  end

  cast_element_present(value, register, resolved_type)
end

#cast_element_present(value, register, resolved_type = nil) ⇒ Object



523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
# File 'lib/lutaml/model/attribute.rb', line 523

def cast_element_present(value, register, resolved_type = nil)
  resolved_type ||= type(register)

  return cast_union(value, nil, register) if union?
  return resolved_type.new(value) if value.is_a?(::Hash) && !hash_type?

  # Special handling for Reference types - pass the metadata
  # (the comparison is attribute-constant; memoize the verdict)
  if reference_type?
    return resolved_type.(value,
                                            @options[:ref_model_class], @options[:ref_key_attribute])
  end

  # The castability verdict is a class-hierarchy fact, immutable
  # per resolved type — check once, not per value (TODO.max-perf/15).
  checked = (@castable_types ||= {}.compare_by_identity)
  unless checked[resolved_type]
    validate_attr_type!(resolved_type)
    checked[resolved_type] = true
  end

  resolved_type.cast(value)
end

#cast_items(value, register) ⇒ Object

Prepare the seed items for a collection. Custom Collection classes cast their own items (idempotently) in #initialize, so hand them a plain array of the existing elements — rebuilding a fresh collection avoids sharing a mutable default across instances. Plain collections cast each element here.



411
412
413
414
415
# File 'lib/lutaml/model/attribute.rb', line 411

def cast_items(value, register)
  return value.to_a if custom_collection?

  value.map { |v| cast_element(v, register) }
end

#cast_present(value, format, register, options = {}) ⇒ Object



899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
# File 'lib/lutaml/model/attribute.rb', line 899

def cast_present(value, format, register, options = {})
  # Namespace-aware type resolution: use type_with_namespace if namespace_uri provided
  namespace_uri = options[:namespace_uri]
  resolved_type = if options[:resolved_type]
                    options[:resolved_type]
                  elsif register && namespace_uri
                    type_with_namespace(register, namespace_uri)
                  else
                    type(register)
                  end
  if (collection_instance?(value) || value.is_a?(Array)) &&
      !value_policy.whole_value?(resolved_type)
    merged_opts = options.merge(resolved_type: resolved_type,
                                converted: true)
    return build_collection(value.map do |v|
      cast(v, format, register, merged_opts)
    end, register: register)
  end

  return value if already_serialized?(resolved_type, value)

  return cast_union(value, format, register) if union?

  # Special handling for Reference types - pass the metadata
  # Check @options[:ref_model_class] which is set when type is { ref: [...] }
  if @options[:ref_model_class] && resolved_type == Lutaml::Model::Type::Reference
    return resolved_type.(value,
                                            @options[:ref_model_class], @options[:ref_key_attribute])
  end

  # Fast path for Type::Value subclasses (String, Integer, Boolean, etc.)
  # These are never Serializable, so skip expensive can_serialize? and needs_conversion? checks
  # Skip if type has custom from_xml/from_json methods (defined on the class itself, not inherited).
  # The probe allocated two Method objects per cast call; the answer is
  # static per type class, so it is resolved once.
  if resolved_type.is_a?(Class) && resolved_type < Lutaml::Model::Type::Value && !self.class.custom_from_probe?(resolved_type)
    return resolved_type.cast(value)
  end

  klass = resolve_polymorphic_class(resolved_type, value, options)
  if can_serialize?(klass, value, format, options)
    propagated = Serialize::DeserializationContext.propagate(options)
    klass.apply_mappings(value, format,
                         propagated.merge(register: register))
  elsif needs_conversion?(klass, value)
    klass.public_send(:"from_#{format}", value)
  else
    # No need to use register#get_class,
    # can_serialize? method already checks if type is Serializable or not.
    Type.lookup(klass).cast(value)
  end
end

#cast_type!(type) ⇒ Object



385
386
387
# File 'lib/lutaml/model/attribute.rb', line 385

def cast_type!(type)
  self.class.cast_type!(type)
end

#cast_value(value, register) ⇒ Object



389
390
391
392
393
394
395
396
397
# File 'lib/lutaml/model/attribute.rb', line 389

def cast_value(value, register)
  if list_like?(value)
    build_collection(cast_items(value, register), register: register)
  elsif coerce_to_collection?(value)
    build_collection(cast_items([value], register), register: register)
  else
    cast_element(value, register)
  end
end

#choice ⇒ Object

min_collection_zero? is provided by CollectionHandler module



993
994
995
# File 'lib/lutaml/model/attribute.rb', line 993

def choice
  @options[:choice]
end

#clear_type_cache ⇒ Object

Clear type resolution caches for this attribute. Called by GlobalContext.clear_caches to ensure stale entries from GC'd TypeContext objects don't persist.



1111
1112
1113
1114
1115
1116
1117
# File 'lib/lutaml/model/attribute.rb', line 1111

def clear_type_cache
  @type_cache&.clear
  @cached_type_default = nil
  @default_type_context = nil
  @type_cache_by_register&.clear
  @type_cache_generation = nil
end

#copy_internal_state_from(source) ⇒ Object

Copy internal state from another Attribute instance. Used by dup to transfer processed state without calling private writers.



1103
1104
1105
1106
# File 'lib/lutaml/model/attribute.rb', line 1103

def copy_internal_state_from(source)
  @raw = source.raw?
  @validations = source.validations
end

#deep_dup ⇒ Object



1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
# File 'lib/lutaml/model/attribute.rb', line 1018

def deep_dup
  # Don't deep_dup the entire options hash because:
  # 1. Lambdas/Procs (like :default) should not be duplicated
  # 2. Classes (like :collection class) are immutable
  # 3. Deep dupping creates circular references when lambdas close over the attribute

  # Selectively copy options using direct type checks to avoid method calls
  duped_options = { skip_validation: true }
  options.each do |key, value|
    duped_options[key] = case value
                         when Symbol, TrueClass, FalseClass, Numeric, Class, Module, Proc, Method, NilClass
                           value # Immutable, don't dup
                         when Range
                           # Only dup if bounds are mutable strings
                           if value.begin.is_a?(String) || (value.end && value.end.is_a?(String))
                             Range.new(value.begin.dup, value.end&.dup, value.exclude_end?)
                           else
                             value # Immutable bounds, safe to reuse
                           end
                         when Hash
                           Utils.deep_dup(value)
                         when Array
                           Utils.deep_dup(value)
                         else
                           value # Keep as-is (might be a complex object)
                         end
  end

  # Skip validation during deep_dup - options are already validated in original
  # This prevents infinite recursion when process_options! tries to access collection
  self.class.new(name, unresolved_type, duped_options).tap do |dup_attr|
    dup_attr.copy_internal_state_from(self)
  end
end

#default(register = Lutaml::Model::Config.default_register, instance_object = nil) ⇒ Object



565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
# File 'lib/lutaml/model/attribute.rb', line 565

def default(register = Lutaml::Model::Config.default_register,
instance_object = nil)
  if instance_object.nil?
    @default_cache ||= {}
    cached = @default_cache[register]
    return cached if cached

    result = cast_value(default_value(register, nil), register)
    if immutable_value?(result)
      @default_cache[register] = result
    end
    result
  else
    cast_value(default_value(register, instance_object), register)
  end
end

#default_set?(register, instance_object = nil) ⇒ Boolean

Returns:

  • (Boolean)


636
637
638
# File 'lib/lutaml/model/attribute.rb', line 636

def default_set?(register, instance_object = nil)
  !Utils.uninitialized?(default_value(register, instance_object))
end

#default_type_context ⇒ Object

Performance: Cache default type context lookup



318
319
320
321
322
323
324
# File 'lib/lutaml/model/attribute.rb', line 318

def default_type_context
  @default_type_context ||= begin
    default_id = Lutaml::Model::Config.default_register
    ctx = GlobalContext.context(default_id)
    ctx || GlobalContext.default_context
  end
end

#default_value(register, instance_object = nil) ⇒ Object



589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
# File 'lib/lutaml/model/attribute.rb', line 589

def default_value(register, instance_object = nil)
  # The kind is fixed at definition; the common case (no default
  # at all) paid three option checks per absent attribute per
  # instantiation before the memo.
  case (@default_kind ||= _default_kind)
  when :none
    Lutaml::Model::UninitializedClass.instance
  when :static
    options[:default]
  when :proc
    if instance_object
      ::Lutaml::Model::Attribute.evaluating_default do
        instance_object.instance_exec(&options[:default])
      end
    else
      options[:default].call
    end
  else # :delegate
    type(register).attributes(register)[to].default(register,
                                                    instance_object)
  end
end

#delegate ⇒ Object



359
360
361
# File 'lib/lutaml/model/attribute.rb', line 359

def delegate
  @options[:delegate]
end

#derived? ⇒ Boolean

Returns:

  • (Boolean)


355
356
357
# File 'lib/lutaml/model/attribute.rb', line 355

def derived?
  !method_name.nil?
end

#enum? ⇒ Boolean

Returns:

  • (Boolean)


561
562
563
# File 'lib/lutaml/model/attribute.rb', line 561

def enum?
  !enum_values.empty?
end

#enum_values ⇒ Object



647
648
649
# File 'lib/lutaml/model/attribute.rb', line 647

def enum_values
  @options.key?(:values) ? @options[:values] : EMPTY_VALUES_ARRAY
end

#execute_validations!(value) ⇒ Object

execute custom validations on the attribute value i.e presence: true, numericality: true, etc



741
742
743
744
745
746
747
748
749
750
751
# File 'lib/lutaml/model/attribute.rb', line 741

def execute_validations!(value)
  return true if Utils.blank?(value)

  memoization_container = {}
  errors = Lutaml::Model::Validator.call(value, validations,
                                         memoization_container)

  return if errors.empty?

  raise Lutaml::Model::ValidationFailedError.new(errors)
end

#extract_register(_context_or_register) ⇒ Object

Extract the Register from the context_or_register argument



289
290
291
292
293
# File 'lib/lutaml/model/attribute.rb', line 289

def extract_register(_context_or_register)
  # Register backward compatibility - now always returns nil
  # Type resolution uses GlobalContext directly
  nil
end

#hash_type? ⇒ Boolean

Returns:

  • (Boolean)


547
548
549
# File 'lib/lutaml/model/attribute.rb', line 547

def hash_type?
  type == Lutaml::Model::Type::Hash
end

#immutable_value?(value) ⇒ Boolean

Returns:

  • (Boolean)


582
583
584
585
586
587
# File 'lib/lutaml/model/attribute.rb', line 582

def immutable_value?(value)
  value.nil? || value.is_a?(Numeric) || value.is_a?(String) ||
    value.is_a?(Symbol) || value == true || value == false ||
    value.equal?(::Lutaml::Model::UninitializedClass.instance) ||
    value.frozen?
end

#initialize_empty? ⇒ Boolean

Returns:

  • (Boolean)


377
378
379
# File 'lib/lutaml/model/attribute.rb', line 377

def initialize_empty?
  @options[:initialize_empty]
end

#list_like?(value) ⇒ Boolean

Plain Arrays count as list input. On singular attributes collection_instance? matches Arrays too (their collection class is Array), preserving the Array so strict cardinality can flag it.

Returns:

  • (Boolean)


402
403
404
# File 'lib/lutaml/model/attribute.rb', line 402

def list_like?(value)
  collection_instance?(value) || (collection? && value.is_a?(::Array))
end

#loaded_type(context_or_register = nil) ⇒ Object

Resolution that never materializes deferred model classes: raises UnknownTypeError for a not-yet-loaded class name. Mapping-time validation uses this so finalizing one mapping cannot fire an autoload that re-enters another model file mid-definition.



180
181
182
183
184
185
# File 'lib/lutaml/model/attribute.rb', line 180

def loaded_type(context_or_register = nil)
  return if unresolved_type.nil?

  context = normalize_context(context_or_register)
  resolver.resolve(unresolved_type, context, materialize: false)
end

#method_name ⇒ Object



373
374
375
# File 'lib/lutaml/model/attribute.rb', line 373

def method_name
  @options[:method_name]
end

#model_instance?(value) ⇒ Boolean

Returns:

  • (Boolean)


874
875
876
877
878
# File 'lib/lutaml/model/attribute.rb', line 874

def model_instance?(value)
  return false unless @options[:ref_model_class]

  value.class.name == @options[:ref_model_class]
end

#no_data?(value) ⇒ Boolean

True when the value is "nothing arrived" rather than data.

nil and the uninitialized sentinel both mean the source carried no value. Neither is something a type can be asked to turn into an instance.

Parameters:

  • value (Object)

Returns:

  • (Boolean)


495
496
497
# File 'lib/lutaml/model/attribute.rb', line 495

def no_data?(value)
  value.nil? || Utils.uninitialized?(value)
end

#normalize_context(context_or_register) ⇒ Object

Normalize register/context to TypeContext for resolution Performance: Optimized to reduce allocations in hot path



297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
# File 'lib/lutaml/model/attribute.rb', line 297

def normalize_context(context_or_register)
  # Fast path for nil - most common case
  return default_type_context if context_or_register.nil?

  # Fast path for TypeContext - no conversion needed
  return context_or_register if context_or_register.is_a?(Lutaml::Model::TypeContext)

  # Handle Register and Symbol cases
  context_id = case context_or_register
               when Lutaml::Model::Register
                 context_or_register.id
               when Symbol
                 context_or_register
               else
                 return GlobalContext.default_context
               end

  GlobalContext.context(context_id) || GlobalContext.default_context
end

#pattern ⇒ Object



640
641
642
# File 'lib/lutaml/model/attribute.rb', line 640

def pattern
  options[:pattern]
end

#polymorphic? ⇒ Boolean

Returns:

  • (Boolean)


340
341
342
# File 'lib/lutaml/model/attribute.rb', line 340

def polymorphic?
  @options[:polymorphic_class]
end

#process_options! ⇒ Object



997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
# File 'lib/lutaml/model/attribute.rb', line 997

def process_options!
  validate_options!(@options)
  if union?
    @options[:union_member_types] =
      Lutaml::Model::Type::Union.validate_members!(@options[:union_member_types])
    Lutaml::Model::Type::Union.validate_combo!(@options)
  end
  # `restrict` merges new options into the SAME attribute object
  # post-construction — the option-derived memos must reset here or
  # collection?/transform keep answering from the pre-restrict state.
  remove_instance_variable(:@collection_option) if defined?(@collection_option)
  remove_instance_variable(:@transform) if defined?(@transform)
  @raw = !!@options[:raw]
  if @raw
    warn "[DEPRECATED] attribute :#{name}, :string, raw: true is deprecated. " \
         "Use map_element \"name\", to: :#{name}, raw: :content instead."
  end
  @validations = @options[:validations]
  set_default_for_collection if collection?
end

#raw? ⇒ Boolean

Collection methods are provided by CollectionHandler module

Returns:

  • (Boolean)


557
558
559
# File 'lib/lutaml/model/attribute.rb', line 557

def raw?
  @raw
end

#reference_key(value) ⇒ Object



865
866
867
868
869
870
871
872
# File 'lib/lutaml/model/attribute.rb', line 865

def reference_key(value)
  return nil unless value
  return value.map { |item| reference_key(item) } if value.is_a?(Array)

  return value.public_send(@options[:ref_key_attribute]) if model_instance?(value)

  value
end

#reference_type? ⇒ Boolean

Returns:

  • (Boolean)


330
331
332
# File 'lib/lutaml/model/attribute.rb', line 330

def reference_type?
  (@reference_type ||= unresolved_type == Lutaml::Model::Type::Reference)
end

#required_value_set?(value) ⇒ Boolean

Returns:

  • (Boolean)


479
480
481
482
483
484
485
# File 'lib/lutaml/model/attribute.rb', line 479

def required_value_set?(value)
  return true unless options[:required]
  return false if value.nil?
  return false if Utils.empty?(value)

  true
end

#resolver ⇒ Object

Cache the resolver reference — GlobalContext.resolver is a singleton that never changes during the process lifetime. Avoids repeated singleton access overhead on every type() call.



160
161
162
# File 'lib/lutaml/model/attribute.rb', line 160

def resolver
  @resolver ||= GlobalContext.resolver
end

#sequenced_appearance_count(element_order, mapped_name, current_index) ⇒ Object

resolved_collection is provided by CollectionHandler module



970
971
972
973
974
975
976
977
978
979
980
981
982
# File 'lib/lutaml/model/attribute.rb', line 970

def sequenced_appearance_count(element_order, mapped_name, current_index)
  elements = element_order[current_index..]
  element_count = elements.take_while do |element|
    element == mapped_name
  end.count
  return element_count if element_count.between?(*resolved_collection.minmax)

  raise Lutaml::Model::ElementCountOutOfRangeError.new(
    mapped_name,
    element_count,
    collection,
  )
end

#serializable?(register) ⇒ Boolean

Returns:

  • (Boolean)


952
953
954
# File 'lib/lutaml/model/attribute.rb', line 952

def serializable?(register)
  type(register) <= Serialize
end

#serializable_type?(register = nil) ⇒ Boolean

Cached version of serializable? check for hot deserialization path Called millions of times in resolve_rule_names_with_type and value_for_rule

Returns:

  • (Boolean)


958
959
960
961
962
963
964
965
966
# File 'lib/lutaml/model/attribute.rb', line 958

def serializable_type?(register = nil)
  register_key = register || :default
  return @serializable_type_cache[register_key] if defined?(@serializable_type_cache) && @serializable_type_cache&.key?(register_key)

  resolved_type = type(register_key)
  result = resolved_type.is_a?(Class) && resolved_type.include?(Serialize)
  @serializable_type_cache ||= {}
  @serializable_type_cache[register_key] = result
end

#serialize(value, format, register, options = {}) ⇒ Object



847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
# File 'lib/lutaml/model/attribute.rb', line 847

def serialize(value, format, register, options = {})
  value ||= build_collection if collection? && initialize_empty?
  return value if value.nil? || Utils.uninitialized?(value)

  resolved_type = options[:resolved_type] || type(register)
  value = reference_key(value) if unresolved_type == Lutaml::Model::Type::Reference
  if collection_instance?(value)
    return serialize_array(value, format, register,
                           options.merge(resolved_type: resolved_type))
  end
  if resolved_type <= Serialize
    return serialize_model(value, format, register,
                           options)
  end

  serialize_value(value, format, resolved_type)
end

#setter ⇒ Object



551
552
553
# File 'lib/lutaml/model/attribute.rb', line 551

def setter
  :"#{@name}="
end

#transform ⇒ Object



366
367
368
369
370
371
# File 'lib/lutaml/model/attribute.rb', line 366

def transform
  # Options are fixed after definition (value_policy memoizes the
  # same way) — the per-call @options[:transform] Hash#[] was hit
  # 2.9 M times on the ISO-13849 parse profile.
  @transform ||= @options[:transform] || EMPTY_TRANSFORM_HASH
end

#transform_export_method ⇒ Object



655
656
657
# File 'lib/lutaml/model/attribute.rb', line 655

def transform_export_method
  transform[:export]
end

#transform_import_method ⇒ Object



651
652
653
# File 'lib/lutaml/model/attribute.rb', line 651

def transform_import_method
  transform[:import]
end

#type(context_or_register = nil) ⇒ Object



187
188
189
190
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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
# File 'lib/lutaml/model/attribute.rb', line 187

def type(context_or_register = nil)
  return if unresolved_type.nil?

  # Performance: Fast path for nil or default register (most common case during deserialization)
  if context_or_register.nil? || context_or_register == :default
    return @cached_type_default ||= begin
      context = normalize_context(context_or_register)
      resolver.resolve(unresolved_type, context)
    end
  end

  # Register/Symbol path: the resolution is a static fact of
  # (attribute, register id), but the old code walked
  # GlobalContext.context — a singleton hop, a delegation, a to_sym
  # normalization and a registry lookup — on every call (2.4 M calls,
  # 3.9 M GlobalContext#context hits per ISO-13849 parse). Cache keyed
  # on the register id itself; a context replaced under the same id
  # bumps GlobalContext.context_generation and flushes the cache.
  register_id = case context_or_register
                when Symbol
                  context_or_register
                when Lutaml::Model::Register
                  context_or_register.id
                end

  if register_id
    cache = (@type_cache_by_register ||= {})
    generation = GlobalContext.context_generation
    if @type_cache_generation != generation
      cache.clear
      @type_cache_generation = generation
    end
    cached = cache[register_id]
    return cached if cached

    context = GlobalContext.context(register_id)
    # An unregistered id falls back to the (thread-local) default
    # context — do not pin that answer in the shared cache.
    return resolver.resolve(unresolved_type, context || GlobalContext.default_context) unless context

    resolved = resolver.resolve(unresolved_type, context)
    cache[register_id] = resolved
    resolved
  elsif context_or_register.is_a?(Lutaml::Model::TypeContext)
    # Performance: Cache per TypeContext identity.
    # When type substitution replaces a TypeContext, the object_id changes,
    # so old cache entries are never hit again (safe invalidation).
    cache_key = context_or_register.object_id
    @type_cache ||= {}
    cached = @type_cache[cache_key]
    return cached if cached

    resolved = resolver.resolve(unresolved_type, context_or_register)
    @type_cache[cache_key] = resolved
    resolved
  else
    @cached_type_default ||= begin
      context = normalize_context(context_or_register)
      resolver.resolve(unresolved_type, context)
    end
  end
end

#type_namespace_class(register = nil) ⇒ Class?

Get namespace class from Type::Value or Model class

Parameters:

  • register (Symbol, nil) (defaults to: nil) —

    register ID for type resolution

Returns:

  • (Class, nil) —

    XmlNamespace class if type has namespace



1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
# File 'lib/lutaml/model/attribute.rb', line 1058

def type_namespace_class(register = nil)
  register_key = register || :default
  return @type_ns_class_cache[register_key] if defined?(@type_ns_class_cache) && @type_ns_class_cache&.key?(register_key)

  # Resolve type namespace via type() which uses GlobalContext.resolver
  resolved_type = type(register_key)
  result = nil

  # Check if type is a Type::Value class
  # Type namespaces are ONLY declared on Type::Value subclasses,
  # not on Serializable models. Serializable models have element
  # namespaces, which are handled separately.
  if resolved_type.is_a?(Class) && resolved_type <= Lutaml::Model::Type::Value
    result = resolved_type.namespace_class
  end

  @type_ns_class_cache ||= {}
  @type_ns_class_cache[register_key] = result
end

#type_namespace_prefix(register = nil) ⇒ String?

Get namespace prefix from type

Parameters:

  • register (Symbol, nil) (defaults to: nil) —

    register ID for type resolution

Returns:

  • (String, nil) —

    namespace prefix



1097
1098
1099
# File 'lib/lutaml/model/attribute.rb', line 1097

def type_namespace_prefix(register = nil)
  type_namespace_class(register)&.prefix_default
end

#type_namespace_uri(register = nil) ⇒ String?

Get namespace URI from type

Parameters:

  • register (Symbol, nil) (defaults to: nil) —

    register ID for type resolution

Returns:

  • (String, nil) —

    namespace URI



1083
1084
1085
1086
1087
1088
1089
1090
# File 'lib/lutaml/model/attribute.rb', line 1083

def type_namespace_uri(register = nil)
  register_key = register || :default
  return @type_ns_uri_cache[register_key] if defined?(@type_ns_uri_cache) && @type_ns_uri_cache&.key?(register_key)

  result = type_namespace_class(register_key)&.uri
  @type_ns_uri_cache ||= {}
  @type_ns_uri_cache[register_key] = result
end

#type_with_namespace(register, namespace_uri = nil) ⇒ Class?

Get type with namespace-aware resolution.

Uses the register's resolve_in_namespace method for version-aware type resolution. Falls back to standard resolution if no namespace or register is provided.

Parameters:

  • register (Lutaml::Model::Register, Symbol, nil) —

    The register or register ID

  • namespace_uri (String, nil) (defaults to: nil) —

    The namespace URI for version awareness

Returns:

  • (Class, nil) —

    The type class or nil



260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
# File 'lib/lutaml/model/attribute.rb', line 260

def type_with_namespace(register, namespace_uri = nil)
  return type(register) unless register && namespace_uri
  return if unresolved_type.nil?

  # Performance: Memoize type resolution per (register, namespace_uri) pair
  # This avoids repeated resolve_in_namespace calls for the same attribute
  @type_with_namespace_cache ||= {}
  cache_key = [register, namespace_uri]
  return @type_with_namespace_cache[cache_key] if @type_with_namespace_cache.key?(cache_key)

  # Resolve register from symbol if needed
  actual_register = if register.is_a?(Symbol)
                      Lutaml::Model::GlobalRegister.lookup(register)
                    else
                      register
                    end

  # If we don't have an actual Register object, fall back to standard resolution
  result = if actual_register.is_a?(Lutaml::Model::Register)
             actual_register.resolve_in_namespace(unresolved_type,
                                                  namespace_uri)
           end
  result ||= type(register)

  @type_with_namespace_cache[cache_key] = result
  result
end

#union? ⇒ Boolean

Returns:

  • (Boolean)


344
345
346
347
348
# File 'lib/lutaml/model/attribute.rb', line 344

def union?
  return @union unless @union.nil?

  @union = unresolved_type == Lutaml::Model::Type::Union
end

#union_member_types ⇒ Object



350
351
352
353
# File 'lib/lutaml/model/attribute.rb', line 350

def union_member_types
  @union_member_types ||=
    @options[:union_member_types].map { |member| cast_type!(member) }
end

#unresolved_type ⇒ Object



326
327
328
# File 'lib/lutaml/model/attribute.rb', line 326

def unresolved_type
  @unresolved_type || @type
end

#valid_collection!(value, caller) ⇒ Object



801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
# File 'lib/lutaml/model/attribute.rb', line 801

def valid_collection!(value, caller)
  if collection_instance?(value) && !collection? &&
      !value_policy.whole_value?(unresolved_type)
    raise Lutaml::Model::CollectionTrueMissingError.new(name,
                                                        caller)
  end

  return true unless collection?

  # Allow any value for unbounded collections
  return true if collection == true

  unless collection_instance?(value)
    # An absent value satisfies a zero minimum and has nothing to size.
    return true if (value.nil? || Utils.uninitialized?(value)) &&
      resolved_collection.min.zero?

    raise Lutaml::Model::CollectionCountOutOfRangeError.new(
      name,
      value,
      collection,
    )
  end

  # cover? rather than between?, so an exclusive range such as (0...5)
  # rejects a count of 5.
  in_range = if resolved_collection.end.infinite?
               value.size >= resolved_collection.begin
             else
               resolved_collection.cover?(value.size)
             end

  unless in_range
    raise Lutaml::Model::CollectionCountOutOfRangeError.new(
      name,
      value,
      collection,
    )
  end

  # Truthy on success: validate_value! chains this with && before the
  # value/pattern/polymorphic/custom checks, so falling through as nil would
  # silently skip them for a valid bounded-range collection.
  true
end

#valid_pattern!(value, _resolved_type) ⇒ Object

Pattern binds actual string values only. For a plain :string attribute every element is a string; for a union the pattern applies to whichever elements took the :string branch (non-string members are exempt). A nil element is skipped along with every other non-string, and Array(value) flattens both plain Arrays and custom Collections so the pattern applies per element instead of to the collection as a whole.



693
694
695
696
697
698
699
700
701
702
703
704
# File 'lib/lutaml/model/attribute.rb', line 693

def valid_pattern!(value, _resolved_type)
  return true unless pattern

  Array(value).each do |item|
    next unless item.is_a?(::String)
    next if pattern.match?(item)

    raise Lutaml::Model::PatternNotMatchedError.new(name, pattern, item)
  end

  true
end

#valid_value!(value) ⇒ Object



659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
# File 'lib/lutaml/model/attribute.rb', line 659

def valid_value!(value)
  # nil is never tested against the value set, whether it arrives as the
  # whole value or as one element of a collection (this method recurses
  # per element). valid_pattern! skips nil the same way, and an unset
  # attribute is validate_required!'s business, not the enum's.
  return true if value.nil?
  return true unless enum?
  return true if Utils.uninitialized?(value)

  # Collection attributes hold multiple values; validate each element
  # against the allowed set rather than the coerced collection itself.
  if value.is_a?(::Array) || collection_instance?(value)
    return value.all? { |v| valid_value!(v) }
  end

  unless valid_value?(value)
    raise Lutaml::Model::InvalidValueError.new(name, value, enum_values)
  end

  true
end

#valid_value?(value) ⇒ Boolean

Returns:

  • (Boolean)


681
682
683
684
685
# File 'lib/lutaml/model/attribute.rb', line 681

def valid_value?(value)
  return true unless options[:values]

  options[:values].include?(value)
end

#validate_attr_type!(resolved_type) ⇒ Object

Public validation contract: mappings check their targets at finalize (lutaml-model#296), the cast path checks per value.



1121
1122
1123
1124
1125
1126
1127
# File 'lib/lutaml/model/attribute.rb', line 1121

def validate_attr_type!(resolved_type)
  return true if resolved_type <= Serializable || resolved_type <= Type::Value
  return true if resolved_type.include?(Serialize)

  raise Lutaml::Model::InvalidAttributeTypeError.new(name,
                                                     resolved_type.name)
end

#validate_choice_content!(elements) ⇒ Object



984
985
986
987
988
989
# File 'lib/lutaml/model/attribute.rb', line 984

def validate_choice_content!(elements)
  return elements.count unless resolved_collection
  return 1 if elements.count.between?(*resolved_collection.minmax)

  elements.each_slice(resolved_collection.max).count
end

#validate_collection_range ⇒ Object



770
771
772
773
774
775
776
777
778
779
780
# File 'lib/lutaml/model/attribute.rb', line 770

def validate_collection_range
  range = @options[:collection]
  return if range == true
  return if custom_collection?

  unless range.is_a?(Range)
    raise ArgumentError, "Invalid collection range: #{range}"
  end

  validate_range!(range)
end

#validate_polymorphic(value, resolved_type) ⇒ Object



753
754
755
756
757
758
759
760
761
762
# File 'lib/lutaml/model/attribute.rb', line 753

def validate_polymorphic(value, resolved_type)
  if value.is_a?(Array)
    return value.all? do |v|
      validate_polymorphic!(v, resolved_type)
    end
  end
  return true unless options[:polymorphic]

  valid_polymorphic_type?(value, resolved_type)
end

#validate_polymorphic!(value, resolved_type) ⇒ Object



764
765
766
767
768
# File 'lib/lutaml/model/attribute.rb', line 764

def validate_polymorphic!(value, resolved_type)
  return true if validate_polymorphic(value, resolved_type)

  raise Lutaml::Model::PolymorphicError.new(value, options, resolved_type)
end

#validate_range!(range) ⇒ Object



782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
# File 'lib/lutaml/model/attribute.rb', line 782

def validate_range!(range)
  if range.begin.nil?
    raise ArgumentError,
          "Invalid collection range: #{range}. Begin must be specified."
  end

  if range.begin.negative?
    raise ArgumentError,
          "Invalid collection range: #{range}. " \
          "Begin must be non-negative."
  end

  if range.end && range.end < range.begin
    raise ArgumentError,
          "Invalid collection range: #{range}. " \
          "End must be greater than or equal to begin."
  end
end

#validate_value!(value, register, instance_object: nil) ⇒ Object

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

Currently there are 2 validations

  1. Value should be from the values list if they are defined e.g values: ["foo", "bar"] is set then any other value for this attribute will raise Lutaml::Model::InvalidValueError

  2. Value count should be between the collection range if defined e.g if collection: 0..5 is set then the value greater then 5 will raise Lutaml::Model::CollectionCountOutOfRangeError



716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
# File 'lib/lutaml/model/attribute.rb', line 716

def validate_value!(value, register, instance_object: nil)
  # Use the default value if the value is nil
  validate_required!(value)

  if value.nil?
    value = cast_value(default_value(register, instance_object),
                       register)
  end
  resolved_type = type(register)
  validate_restriction_configuration!(resolved_type)

  # Shape before contents. An over-count is a cardinality violation, not
  # an enum or pattern one, and checking it first keeps those predicates
  # from reporting on a value whose shape is already wrong.
  valid_collection!(value, instance_object&.class) &&
    valid_value!(value) &&
    valid_pattern!(value, resolved_type) &&
    validate_polymorphic!(value, resolved_type) &&
    execute_validations!(value)

  validate_restriction_values!(value, resolved_type)
end

#value_map_boolean? ⇒ Boolean

Returns:

  • (Boolean)


334
335
336
337
338
# File 'lib/lutaml/model/attribute.rb', line 334

def value_map_boolean?
  (@value_map_boolean ||=
     type == Lutaml::Model::Type::Boolean ||
     unresolved_type == Lutaml::Model::Type::Boolean)
end

#value_policy ⇒ Object

The value-shaping policy for this attribute. Constructed lazily so the collection/union/ref flags are settled; memoized because they are fixed after definition.



167
168
169
170
171
172
173
# File 'lib/lutaml/model/attribute.rb', line 167

def value_policy
  @value_policy ||= ValuePolicy.new(
    collection: collection?,
    union: union?,
    reference: !@options[:ref_model_class].nil?,
  )
end