Class: Literal::OpenAPI::Adapters::BaseAdapter

Inherits:
Object
  • Object
show all
Defined in:
lib/literal/openapi/adapters/base_adapter.rb

Direct Known Subclasses

OpenAPI3_0

Constant Summary collapse

PRIMITIVE_MAP =
{
  ::String => { "type" => "string" },
  ::Integer => { "type" => "integer" },
  ::Float => { "type" => "number" },
  ::Numeric => { "type" => "number" },
  ::Symbol => { "type" => "string" },
  ::Date => { "type" => "string", "format" => "date" },
  ::Time => { "type" => "string", "format" => "date-time" },
  ::DateTime => { "type" => "string", "format" => "date-time" },
  ::TrueClass => { "type" => "boolean" },
  ::FalseClass => { "type" => "boolean" },
  ::NilClass => { "type" => "null" }
}.freeze
PROPERTY_KEY_ORDER =

Canonical property-key order for emitted schemas. Puts type + content first, with nullable LAST. Any keys not in this list preserve their insertion order immediately before nullable. Keeping this deterministic lets downstream consumers diff schema YAML reliably.

%w[
  type format items $ref
  properties additionalProperties required
  description enum
  minimum maximum exclusive_minimum exclusive_maximum multiple_of
  min_length max_length pattern
  min_items max_items unique_items
  min_properties max_properties
  default const examples
  nullable
].freeze

Instance Method Summary collapse

Instance Method Details

#build_schema(klass) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/literal/openapi/adapters/base_adapter.rb', line 27

def build_schema(klass)
  # Track classes currently being built to catch reference cycles
  # from bare (non-`_Ref`) mutually-recursive serializers. Without
  # this, two serializers referencing each other inline blow the
  # stack via unbounded `inline_schema` recursion.
  @build_stack ||= []
  if @build_stack.include?(klass)
    raise Literal::OpenAPI::Error,
          "Cycle detected while inlining #{klass.inspect}. Use `_Ref(#{klass})` to emit a $ref instead."
  end

  @build_stack.push(klass)
  begin
    build_schema_body(klass)
  ensure
    @build_stack.pop
  end
end

#convert_class_type(type) ⇒ Object



193
194
195
196
197
198
199
200
201
# File 'lib/literal/openapi/adapters/base_adapter.rb', line 193

def convert_class_type(type)
  # `_Class(X)` — if X is a Serializable, treat it as a ref.
  # Otherwise emit a plain object.
  if type.type.respond_to?(:openapi_schema)
    { "$ref" => "#/components/schemas/#{schema_name(type.type)}" }
  else
    { "type" => "object" }
  end
end

#convert_nilable(_type) ⇒ Object

Version-specific: override in subclass.

Raises:

  • (NotImplementedError)


166
167
168
# File 'lib/literal/openapi/adapters/base_adapter.rb', line 166

def convert_nilable(_type)
  raise NotImplementedError, "#{self.class}#convert_nilable"
end

#convert_oneof(_types, include_null:) ⇒ Object

Version-specific: override in subclass.

Raises:

  • (NotImplementedError)


171
172
173
# File 'lib/literal/openapi/adapters/base_adapter.rb', line 171

def convert_oneof(_types, include_null:)
  raise NotImplementedError, "#{self.class}#convert_oneof"
end

#convert_primitive(klass) ⇒ Object



203
204
205
206
207
208
209
210
211
212
213
214
215
# File 'lib/literal/openapi/adapters/base_adapter.rb', line 203

def convert_primitive(klass)
  mapped = PRIMITIVE_MAP[klass]
  return mapped.dup if mapped

  # A bare serializer class (not wrapped in _Ref) inlines its schema.
  # Use `_Ref(X)` in a `prop` declaration to emit a `$ref` instead.
  if klass.respond_to?(:openapi_schema)
    inline_schema(klass)
  else
    raise Literal::OpenAPI::UnknownTypeError,
          "Cannot convert #{klass.inspect} — not in PRIMITIVE_MAP and no openapi_schema method."
  end
end

#convert_ref(type) ⇒ Object



189
190
191
# File 'lib/literal/openapi/adapters/base_adapter.rb', line 189

def convert_ref(type)
  { "$ref" => "#/components/schemas/#{schema_name(type.type)}" }
end

#convert_type(type) ⇒ Object



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
# File 'lib/literal/openapi/adapters/base_adapter.rb', line 127

def convert_type(type)
  case type
  when Literal::OpenAPI::Types::RefType
    convert_ref(type)
  when Literal::Types::NilableType
    convert_nilable(type)
  when Literal::Types::ArrayType
    { "type" => "array", "items" => convert_type(type.type) }
  when Literal::Types::BooleanType
    { "type" => "boolean" }
  when Literal::Types::AnyType, Literal::Types::VoidType
    {}
  when Literal::Types::HashType
    { "type" => "object", "additionalProperties" => convert_type(type.value_type) }
  when Literal::Types::UnionType
    convert_union(type)
  when Literal::Types::ConstraintType
    # Strip the constraint and convert the underlying class (e.g. _String? → String).
    # Range/property constraints are not mapped to OpenAPI yet — see TODOS.
    convert_type(type.object_constraints.first)
  when Literal::Types::IntersectionType
    # Intersection is used by enum-wrapping; convert the first non-predicate member.
    non_predicate = type.types.reject { |t| t.is_a?(Literal::Types::PredicateType) }
    if non_predicate.empty?
      raise Literal::OpenAPI::UnknownTypeError,
            "IntersectionType must have a concrete member"
    end

    convert_type(non_predicate.first)
  when Literal::Types::ClassType
    convert_class_type(type)
  when Module
    convert_primitive(type)
  else
    raise Literal::OpenAPI::UnknownTypeError, "Cannot convert #{type.inspect} (#{type.class})"
  end
end

#convert_union(type) ⇒ Object



175
176
177
178
179
180
181
182
183
184
185
186
187
# File 'lib/literal/openapi/adapters/base_adapter.rb', line 175

def convert_union(type)
  members = type.to_a
  nil_members, non_nil = members.partition(&:nil?)

  if nil_members.any? && non_nil.length == 1
    # Single non-nil member with nil — same semantics as NilableType
    convert_nilable(Literal::Types::NilableType.new(non_nil.first))
  elsif nil_members.any?
    convert_oneof(non_nil, include_null: true)
  else
    convert_oneof(non_nil, include_null: false)
  end
end

#inline_schema(klass) ⇒ Object



217
218
219
# File 'lib/literal/openapi/adapters/base_adapter.rb', line 217

def inline_schema(klass)
  klass.openapi_schema(adapter: self)
end

#ref_schema?(schema) ⇒ Boolean

Detect whether a converted schema is a $ref (pure or wrapped in an anyOf-null). These shapes drop sibling keys in the emitted output because OpenAPI 3.0 forbids siblings on ‘$ref`.

Returns:

  • (Boolean)


231
232
233
234
235
236
237
238
239
# File 'lib/literal/openapi/adapters/base_adapter.rb', line 231

def ref_schema?(schema)
  return false unless schema.is_a?(::Hash)
  return true if schema.keys == ["$ref"]

  any_of = schema["anyOf"]
  return false unless any_of.is_a?(::Array)

  any_of.any? { |m| m.is_a?(::Hash) && m.key?("$ref") }
end

#reorder_property_keys(schema) ⇒ Object



257
258
259
260
261
262
263
264
265
266
267
268
269
270
# File 'lib/literal/openapi/adapters/base_adapter.rb', line 257

def reorder_property_keys(schema)
  return schema unless schema.is_a?(::Hash)

  result = {}
  PROPERTY_KEY_ORDER.each { |k| result[k] = schema[k] if schema.key?(k) }
  # Preserve any unknown keys in their original position, before nullable.
  schema.each_key do |k|
    next if PROPERTY_KEY_ORDER.include?(k)
    next if result.key?(k)

    result[k] = schema[k]
  end
  result
end

#schema_name(klass) ⇒ Object



221
222
223
224
225
226
# File 'lib/literal/openapi/adapters/base_adapter.rb', line 221

def schema_name(klass)
  name = klass.name
  raise Literal::OpenAPI::Error, "Anonymous class #{klass.inspect} cannot be ref'd" if name.nil?

  name.gsub("::", ".").delete_suffix("Serializer")
end