Module: Lutaml::Model::Serialize::AttributeDefinition

Included in:
ClassMethods
Defined in:
lib/lutaml/model/serialize/attribute_definition.rb

Overview

Handles attribute definition methods for Serialize::ClassMethods

Extracted from serialize.rb to improve code organization. Provides methods for defining and validating model attributes.

Instance Method Summary collapse

Instance Method Details

#any_importable_models?Boolean

Check if there are any importable models

Returns:

  • True if there are pending imports



234
235
236
# File 'lib/lutaml/model/serialize/attribute_definition.rb', line 234

def any_importable_models?
  importable_choices.any? || importable_models.any?
end

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

Define an attribute for the model

Parameters:

  • The attribute name

  • The attribute type

  • (defaults to: {})

    Attribute options

Returns:

  • The created attribute



187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
# File 'lib/lutaml/model/serialize/attribute_definition.rb', line 187

def attribute(name, type, options = {})
  type, options = process_type_hash(type, options) if type.is_a?(::Hash)

  if type.is_a?(::Array)
    options = options.merge(union_member_types: type)
    type = Lutaml::Model::Type::Union
  end

  # Handle direct method option in options hash
  if options[:method]
    options[:method_name] = options.delete(:method)
  end

  attr = Attribute.new(name, type, options)
  @attributes[name] = attr
  @merged_attributes_cache = nil
  define_attribute_methods(attr)

  attr
end

#define_attribute_methods(attr, register = nil) ⇒ Object

Define attribute methods on the model class

Parameters:

  • The attribute to define methods for

  • (defaults to: nil)

    The register for type resolution



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/lutaml/model/serialize/attribute_definition.rb', line 15

def define_attribute_methods(attr, register = nil)
  name = attr.name
  register_id = extract_register_id(register)

  if attr.enum?
    add_enum_methods_to_model(
      model,
      name,
      attr.options[:values],
      collection: attr.options[:collection],
    )
  elsif attr.derived? && name != attr.method_name
    unless method_defined?(name, false)
      define_method(name) do
        value = public_send(attr.method_name)
        # Cast the derived value to the specified type. cast_derived,
        # not cast_element: this reader is its own casting entry point,
        # so it needs the same "nothing arrived, nothing to cast" rule
        # the writers get, and a collection has to come back as one.
        attr.cast_derived(value, register_id)
      end
    end
  elsif attr.unresolved_type == Lutaml::Model::Type::Reference
    define_reference_methods(name, register_id)
  else
    define_regular_attribute_methods(name, attr)
  end
end

#define_reference_methods(name, register) ⇒ Object

Define reference-type attribute methods

Reference types store a reference key that can be resolved to the actual object.

Parameters:

  • The attribute name

  • The register ID



51
52
53
54
55
56
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
# File 'lib/lutaml/model/serialize/attribute_definition.rb', line 51

def define_reference_methods(name, register)
  register_id = register
  attr = attributes[name]

  unless method_defined?(:"#{name}_ref", false)
    define_method("#{name}_ref") do
      instance_variable_get(:"@#{name}_ref")
    end
  end

  key_method_name = if attr.options[:collection]
                      Utils.pluralize(attr.options[:ref_key_attribute].to_s)
                    else
                      attr.options[:ref_key_attribute]
                    end

  unless method_defined?(:"#{name}_#{key_method_name}", false)
    define_method("#{name}_#{key_method_name}") do
      ref = instance_variable_get(:"@#{name}_ref")
      # attr.reference_key first: once a collection reader has stored
      # its resolved objects, the key has to come back off the object.
      resolve_reference_key(attr.reference_key(ref))
    end
  end

  unless method_defined?(name, false)
    if attr.options[:collection]
      define_method(name) do
        materialize_reference_collection(name)
      end
    else
      define_method(name) do
        ref = instance_variable_get(:"@#{name}_ref")
        resolve_reference_value(ref)
      end
    end
  end

  unless method_defined?(:"#{name}=", false)
    define_method(:"#{name}=") do |value|
      value_set_for(name)
      casted_value = value
      unless casted_value.is_a?(Lutaml::Model::Type::Reference)
        casted_value = attr.cast_value(value, register_id)
      end

      instance_variable_set(:"@#{name}_ref", casted_value)

      resolved_reference = resolve_reference_key(casted_value)
      instance_variable_set(:"@#{name}", resolved_reference)
    end
  end
end

#define_regular_attribute_methods(name, attr) ⇒ Object

Define regular (non-reference, non-enum) attribute methods

Parameters:

  • The attribute name

  • The attribute definition



109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
# File 'lib/lutaml/model/serialize/attribute_definition.rb', line 109

def define_regular_attribute_methods(name, attr)
  # For collection attributes, the getter accepts an optional argument
  # for builder-style syntax: g.member(item) appends to the collection
  if attr.collection?
    define_method(name) do |*args|
      if args.empty?
        materialize_lazy_collection(name)
      else
        # Builder-style: g.member(item) appends to collection
        value = args.first
        current = instance_variable_get(:"@#{name}") || []
        new_value = current.is_a?(Array) ? current + [value] : value
        instance_variable_set(:"@#{name}", new_value)
        record_mutation(name, value)
        value
      end
    end
  else
    # For non-collection attributes, getter accepts optional argument
    # for builder-style syntax: g.description(value) sets the value.
    # Tracking happens inside the setter, so no duplicate call here.
    define_method(name) do |*args|
      if args.empty?
        instance_variable_get(:"@#{name}")
      else
        public_send(:"#{name}=", args.first)
        args.first
      end
    end
  end

  enum_shorthand_names = instance_variable_get(:@__enum_shorthand_names__) || Set.new
  # Opal's Module#method_defined? only accepts 1 arg (MRI accepts
  # the optional `inherit` flag). Skip the flag there — the
  # difference only matters for inherited-method filtering.
  setter_defined = if Lutaml::Model.opal?
                     method_defined?(:"#{name}=")
                   else
                     method_defined?(:"#{name}=", false)
                   end
  unless setter_defined && !enum_shorthand_names.include?(name.to_s)
    if attr.collection?
      define_method(:"#{name}=") do |value|
        value_set_for(name)
        value = attr.cast_value(value, lutaml_register)
        # Preserve the frozen sentinel when the deserialization pipeline
        # would overwrite it with nil/UninitializedClass (meaning "no data
        # found for this collection"). This maintains the zero-allocation
        # guarantee for unused collections. The sentinel is replaced with
        # a real Array only when actual data is set.
        current = instance_variable_get(:"@#{name}")
        if current.equal?(LAZY_EMPTY_COLLECTION) &&
            (value.nil? || Lutaml::Model::Utils.uninitialized?(value))
          # Sentinel stays — no allocation for truly empty collections
        else
          instance_variable_set(:"@#{name}", value)
        end
        # Track one entry per item so element_order reflects the
        # number of <name> elements that will be emitted.
        record_mutation_collection(name, value)
      end
    else
      define_method(:"#{name}=") do |value|
        value_set_for(name)
        value = attr.cast_value(value, lutaml_register)
        instance_variable_set(:"@#{name}", value)
        record_mutation(name, value)
      end
    end
  end
end

#restrict(name, options = {}) ⇒ Symbol

Restrict options on an existing attribute

Parameters:

  • The attribute name to restrict

  • (defaults to: {})

    New options to merge

Returns:

  • The attribute name



213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
# File 'lib/lutaml/model/serialize/attribute_definition.rb', line 213

def restrict(name, options = {})
  register_id = options.delete(:register) || Lutaml::Model::Config.default_register

  if !@attributes.key?(name) && !register_record(register_id)&.dig(
    :attributes, name
  )
    return restrict_attributes[name] = options if any_importable_models?

    raise Lutaml::Model::UndefinedAttributeError.new(name, self)
  end

  validate_attribute_options!(name, options)
  attr = attributes(register_id)[name]
  attr.options.merge!(options)
  attr.process_options!
  name
end

#validate_attribute_options!(name, options) ⇒ Object

Validate attribute options

Raises:

  • If invalid options are present

Parameters:

  • The attribute name

  • The options to validate



243
244
245
246
247
248
249
# File 'lib/lutaml/model/serialize/attribute_definition.rb', line 243

def validate_attribute_options!(name, options)
  invalid_opts = options.keys - Attribute::ALLOWED_OPTIONS
  return if invalid_opts.empty?

  raise Lutaml::Model::InvalidAttributeOptionsError.new(name,
                                                        invalid_opts)
end