Module: Dolibarr::Api::Polymorphism

Defined in:
lib/dolibarr-api/polymorphism.rb

Overview

Runtime support for anyOf/oneOf candidate resolution. Casts raw deserialized data (Hash/Array/primitive) against a declared candidate type name and returns the matching value, or nil when it does not match.

Candidate type names are plain OpenAPI-Generator Ruby type declarations (e.g. 'Integer', "Array", "Hash<String, Vector>", or a bare model name resolved under Dolibarr::Api::Models). This mirrors the type-name dispatch used by the stock ruby generator's find_and_cast_into_type,

adapted to the idiomatic Models

namespace and attribute DSL.

Constant Summary collapse

ARRAY_TYPE =
/\AArray<(?<sub_type>.+)>\z/
HASH_TYPE =
/\AHash<String, ?(?<sub_type>.+)>\z/

Class Method Summary collapse

Class Method Details

.cast(type_name, data) ⇒ Object

Public entry point used by generated anyOf/oneOf wrappers. Returns the matching value, or nil when no candidate matched.



26
27
28
29
# File 'lib/dolibarr-api/polymorphism.rb', line 26

def self.cast(type_name, data)
  result = cast_raw(type_name, data)
  result.equal?(NO_MATCH) ? nil : result
end

.coerce(type_name, data) ⇒ Object

Non-validating structural coercion used by from_hash deserialization. Unlike cast/cast_raw (which gate on valid? to pick the right anyOf/oneOf candidate), coerce never rejects data: it builds the best typed representation it can and falls back to returning the data unchanged when it cannot resolve a type. This ensures deserialization never silently drops a valid-but-incomplete nested object.



114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
# File 'lib/dolibarr-api/polymorphism.rb', line 114

def self.coerce(type_name, data)
  return nil if data.nil?

  case type_name
  when 'Boolean', 'Integer', 'String', 'Object', 'Hash', nil
    data
  when 'Float'
    data.is_a?(Numeric) ? data.to_f : data
  when 'Time'
    coerce_time(data)
  when ARRAY_TYPE
    sub_type = Regexp.last_match[:sub_type]
    data.is_a?(Array) ? data.map { |item| coerce(sub_type, item) } : data
  when HASH_TYPE
    sub_type = Regexp.last_match[:sub_type]
    data.is_a?(Hash) ? data.transform_values { |value| coerce(sub_type, value) } : data
  else
    coerce_model(type_name, data)
  end
end