Class: Lutaml::Model::Attribute

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

Constant Summary collapse

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
].freeze
MODEL_STRINGS =
[
  Lutaml::Model::Type::String,
  "String",
  :string,
].freeze
CHILD_PROPAGATION_KEYS =

Keys that are safe to propagate from parent to child deserialization. Parent-internal keys (namespace_uri, resolved_type, converted) are intentionally excluded — children must derive their own context.

%i[
  lutaml_parent
  lutaml_root
  default_namespace
  import_declaration_plan
  polymorphic
  collection
  render_empty
  render_nil
  cdata
].freeze
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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from CollectionHandler

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

Constructor Details

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

Returns a new instance of Attribute.



107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
# File 'lib/lutaml/model/attribute.rb', line 107

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

#nameObject (readonly)

Returns the value of attribute name.



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

def name
  @name
end

#optionsObject (readonly)

Returns the value of attribute options.



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

def options
  @options
end

#validationsObject



276
277
278
# File 'lib/lutaml/model/attribute.rb', line 276

def validations
  @options[:validations]
end

Class Method Details

.cast_from_string!(type) ⇒ Object



101
102
103
104
105
# File 'lib/lutaml/model/attribute.rb', line 101

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



95
96
97
98
99
# File 'lib/lutaml/model/attribute.rb', line 95

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

.cast_type!(type) ⇒ Object



85
86
87
88
89
90
91
92
93
# File 'lib/lutaml/model/attribute.rb', line 85

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

.format_specific_warn_namesObject



77
78
79
# File 'lib/lutaml/model/attribute.rb', line 77

def self.format_specific_warn_names
  @format_specific_warn_names
end

.warn_on_override_namesObject



81
82
83
# File 'lib/lutaml/model/attribute.rb', line 81

def self.warn_on_override_names
  WARN_ON_OVERRIDE + @format_specific_warn_names
end

Instance Method Details

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



564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
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
# File 'lib/lutaml/model/attribute.rb', line 564

def cast(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)
    return build_collection(value.map do |v|
      cast(v, format, register,
           options.merge(resolved_type: resolved_type, converted: true))
    end)
  end

  return value if already_serialized?(resolved_type, value)

  # 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)
  if resolved_type.is_a?(Class) && resolved_type < Lutaml::Model::Type::Value
    has_custom_from_xml = resolved_type.respond_to?(:from_xml) &&
      resolved_type.method(:from_xml).owner != Lutaml::Model::Type::Value
    has_custom_from_json = resolved_type.respond_to?(:from_json) &&
      resolved_type.method(:from_json).owner != Lutaml::Model::Type::Value
    return resolved_type.cast(value) unless has_custom_from_xml || has_custom_from_json
  end

  klass = resolve_polymorphic_class(resolved_type, value, options)
  if can_serialize?(klass, value, format, options)
    propagated = options.slice(*CHILD_PROPAGATION_KEYS)
    klass.apply_mappings(value, format,
                         propagated.merge(register: register))
  elsif needs_conversion?(klass, value)
    klass.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_element(value, register) ⇒ Object



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

def cast_element(value, register)
  resolved_type = type(register)
  return resolved_type.new(value) if value.is_a?(::Hash) && !hash_type?

  # Special handling for Reference types - pass the metadata
  if unresolved_type == Lutaml::Model::Type::Reference
    return resolved_type.(value,
                                            @options[:ref_model_class], @options[:ref_key_attribute])
  end

  validate_attr_type!(resolved_type)

  resolved_type.cast(value)
end

#cast_type!(type) ⇒ Object



280
281
282
# File 'lib/lutaml/model/attribute.rb', line 280

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

#cast_value(value, register) ⇒ Object



284
285
286
287
288
# File 'lib/lutaml/model/attribute.rb', line 284

def cast_value(value, register)
  return cast_element(value, register) unless collection_instance?(value)

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

#choiceObject

min_collection_zero? is provided by CollectionHandler module



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

def choice
  @options[:choice]
end

#deep_dupObject



667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
# File 'lib/lutaml/model/attribute.rb', line 667

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|
    # Copy already-processed instance variables directly
    dup_attr.send(:raw=, @raw)
    dup_attr.send(:validations=, @validations)
  end
end

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



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

def default(register = Lutaml::Model::Config.default_register,
instance_object = nil)
  cast_value(default_value(register, instance_object), register)
end

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

Returns:

  • (Boolean)


353
354
355
# File 'lib/lutaml/model/attribute.rb', line 353

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

#default_type_contextObject

Performance: Cache default type context lookup



237
238
239
240
241
242
243
# File 'lib/lutaml/model/attribute.rb', line 237

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



336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
# File 'lib/lutaml/model/attribute.rb', line 336

def default_value(register, instance_object = nil)
  if delegate
    type(register).attributes(register)[to].default(register,
                                                    instance_object)
  elsif options[:default].is_a?(Proc)
    if instance_object
      instance_object.instance_exec(&options[:default])
    else
      options[:default].call
    end
  elsif options.key?(:default)
    options[:default]
  else
    Lutaml::Model::UninitializedClass.instance
  end
end

#delegateObject



257
258
259
# File 'lib/lutaml/model/attribute.rb', line 257

def delegate
  @options[:delegate]
end

#derived?Boolean

Returns:

  • (Boolean)


253
254
255
# File 'lib/lutaml/model/attribute.rb', line 253

def derived?
  !method_name.nil?
end

#enum?Boolean

Returns:

  • (Boolean)


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

def enum?
  !enum_values.empty?
end

#enum_valuesObject



364
365
366
# File 'lib/lutaml/model/attribute.rb', line 364

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



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

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



208
209
210
211
212
# File 'lib/lutaml/model/attribute.rb', line 208

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)


313
314
315
# File 'lib/lutaml/model/attribute.rb', line 313

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

#initialize_empty?Boolean

Returns:

  • (Boolean)


272
273
274
# File 'lib/lutaml/model/attribute.rb', line 272

def initialize_empty?
  @options[:initialize_empty]
end

#method_nameObject



268
269
270
# File 'lib/lutaml/model/attribute.rb', line 268

def method_name
  @options[:method_name]
end

#model_instance?(value) ⇒ Boolean

Returns:

  • (Boolean)


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

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

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

#normalize_context(context_or_register) ⇒ Object

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



216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
# File 'lib/lutaml/model/attribute.rb', line 216

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

#patternObject



357
358
359
# File 'lib/lutaml/model/attribute.rb', line 357

def pattern
  options[:pattern]
end

#polymorphic?Boolean

Returns:

  • (Boolean)


249
250
251
# File 'lib/lutaml/model/attribute.rb', line 249

def polymorphic?
  @options[:polymorphic_class]
end

#process_options!Object



660
661
662
663
664
665
# File 'lib/lutaml/model/attribute.rb', line 660

def process_options!
  validate_options!(@options)
  @raw = !!@options[:raw]
  @validations = @options[:validations]
  set_default_for_collection if collection?
end

#raw?Boolean

Collection methods are provided by CollectionHandler module

Returns:

  • (Boolean)


323
324
325
# File 'lib/lutaml/model/attribute.rb', line 323

def raw?
  @raw
end

#reference_key(value) ⇒ Object



548
549
550
551
552
553
554
555
# File 'lib/lutaml/model/attribute.rb', line 548

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

#required_value_set?(value) ⇒ Boolean

Returns:

  • (Boolean)


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

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

  true
end

#resolverObject

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.



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

def resolver
  @resolver ||= GlobalContext.resolver
end

#sequenced_appearance_count(element_order, mapped_name, current_index) ⇒ Object

resolved_collection is provided by CollectionHandler module



633
634
635
636
637
638
639
640
641
642
643
644
645
# File 'lib/lutaml/model/attribute.rb', line 633

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)


615
616
617
# File 'lib/lutaml/model/attribute.rb', line 615

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)


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

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



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

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)
  serialize_options = options.merge(resolved_type: resolved_type)
  value = reference_key(value) if unresolved_type == Lutaml::Model::Type::Reference
  if collection_instance?(value)
    return serialize_array(value, format, register,
                           serialize_options)
  end
  if resolved_type <= Serialize
    return serialize_model(value, format, register,
                           options)
  end

  serialize_value(value, format, resolved_type)
end

#setterObject



317
318
319
# File 'lib/lutaml/model/attribute.rb', line 317

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

#transformObject



264
265
266
# File 'lib/lutaml/model/attribute.rb', line 264

def transform
  @options[:transform] || EMPTY_TRANSFORM_HASH
end

#transform_export_methodObject



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

def transform_export_method
  transform[:export]
end

#transform_import_methodObject



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

def transform_import_method
  transform[:import]
end

#type(context_or_register = nil) ⇒ Object



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

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

  # Non-default register path: resolve directly without normalize_context
  # when context_or_register is already a TypeContext or Symbol (common cases)
  context = case context_or_register
            when Lutaml::Model::TypeContext
              context_or_register
            when Symbol
              GlobalContext.context(context_or_register) || GlobalContext.default_context
            when Lutaml::Model::Register
              GlobalContext.context(context_or_register.id) || GlobalContext.default_context
            else
              GlobalContext.default_context
            end

  # 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.object_id
  @type_cache ||= {}
  cached = @type_cache[cache_key]
  return cached if cached

  resolved = resolver.resolve(unresolved_type, context)
  @type_cache[cache_key] = resolved
  resolved
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



709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
# File 'lib/lutaml/model/attribute.rb', line 709

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



748
749
750
# File 'lib/lutaml/model/attribute.rb', line 748

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



734
735
736
737
738
739
740
741
# File 'lib/lutaml/model/attribute.rb', line 734

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



179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
# File 'lib/lutaml/model/attribute.rb', line 179

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.respond_to?(:resolve_in_namespace)
             actual_register.resolve_in_namespace(unresolved_type,
                                                  namespace_uri)
           end
  result ||= type(register)

  @type_with_namespace_cache[cache_key] = result
  result
end

#unresolved_typeObject



245
246
247
# File 'lib/lutaml/model/attribute.rb', line 245

def unresolved_type
  @unresolved_type || @type
end

#valid_collection!(value, caller) ⇒ Object



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
# File 'lib/lutaml/model/attribute.rb', line 491

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

  return true unless collection?

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

  unless (Utils.uninitialized?(value) && resolved_collection.min.zero?) || collection_instance?(value)
    raise Lutaml::Model::CollectionCountOutOfRangeError.new(
      name,
      value,
      collection,
    )
  end

  return true unless resolved_collection.is_a?(Range)

  if resolved_collection.is_a?(Range) && resolved_collection.end.infinite?
    if value.size < resolved_collection.begin
      raise Lutaml::Model::CollectionCountOutOfRangeError.new(
        name,
        value,
        collection,
      )
    end
  elsif resolved_collection.is_a?(Range) && !resolved_collection.cover?(value.size)
    raise Lutaml::Model::CollectionCountOutOfRangeError.new(
      name,
      value,
      collection,
    )
  end
end

#valid_pattern!(value, resolved_type) ⇒ Object



394
395
396
397
398
399
400
401
402
403
# File 'lib/lutaml/model/attribute.rb', line 394

def valid_pattern!(value, resolved_type)
  return true unless resolved_type == Lutaml::Model::Type::String
  return true unless pattern

  unless pattern.match?(value)
    raise Lutaml::Model::PatternNotMatchedError.new(name, pattern, value)
  end

  true
end

#valid_value!(value) ⇒ Object



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

def valid_value!(value)
  return true if value.nil? && singular?
  return true unless enum?
  return true if Utils.uninitialized?(value)

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

  true
end

#valid_value?(value) ⇒ Boolean

Returns:

  • (Boolean)


388
389
390
391
392
# File 'lib/lutaml/model/attribute.rb', line 388

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

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

#validate_choice_content!(elements) ⇒ Object



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

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_rangeObject



460
461
462
463
464
465
466
467
468
469
470
# File 'lib/lutaml/model/attribute.rb', line 460

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



443
444
445
446
447
448
449
450
451
452
# File 'lib/lutaml/model/attribute.rb', line 443

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



454
455
456
457
458
# File 'lib/lutaml/model/attribute.rb', line 454

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



472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
# File 'lib/lutaml/model/attribute.rb', line 472

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, resolver = 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`


415
416
417
418
419
420
421
422
423
424
425
426
427
# File 'lib/lutaml/model/attribute.rb', line 415

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

  value = resolver&.default if value.nil?
  resolved_type = type(register)

  valid_value!(value) &&
    valid_collection!(value, self) &&
    valid_pattern!(value, resolved_type) &&
    validate_polymorphic!(value, resolved_type) &&
    execute_validations!(value)
end