Module: Spikard::Schema

Defined in:
lib/spikard/schema.rb

Overview

Schema extraction helpers for Ruby type systems

Supports:

  • Plain JSON Schema (Hash)

  • Dry::Schema with :json_schema extension

  • Dry::Struct (Dry-Types)

Examples:

With Dry::Schema

require 'dry-schema'
Dry::Schema.load_extensions(:json_schema)

UserSchema = Dry::Schema.JSON do
  required(:email).filled(:str?)
  required(:age).filled(:int?)
end

schema = Spikard::Schema.extract_json_schema(UserSchema)

With Dry::Struct

require 'dry-struct'

class User < Dry::Struct
  attribute :email, Types::String
  attribute :age, Types::Integer
end

schema = Spikard::Schema.extract_json_schema(User)

With plain JSON Schema

schema_hash = {
  "type" => "object",
  "properties" => {
    "email" => { "type" => "string" },
    "age" => { "type" => "integer" }
  },
  "required" => ["email", "age"]
}

schema = Spikard::Schema.extract_json_schema(schema_hash)

Class Method Summary collapse

Class Method Details

.extract_json_schema(schema_source) ⇒ Hash?

Extract JSON Schema from various Ruby schema sources

Parameters:

  • schema_source (Object)

    The schema source (Hash, Dry::Schema, Dry::Struct class)

Returns:

  • (Hash, nil)

    JSON Schema hash or nil if extraction fails



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/spikard/schema.rb', line 51

def extract_json_schema(schema_source)
  return nil if schema_source.nil?

  # 1. Check if plain JSON Schema hash
  return schema_source if schema_source.is_a?(Hash) && json_schema_hash?(schema_source)

  # 2. Check for Dry::Schema with json_schema extension
  return extract_from_dry_schema(schema_source) if dry_schema?(schema_source)

  # 3. Check for Dry::Struct (Dry-Types)
  return extract_from_dry_struct(schema_source) if dry_struct_class?(schema_source)

  # 4. Unknown type
  warn "Spikard: Unable to extract JSON Schema from #{schema_source.class}. " \
       'Supported types: Hash, Dry::Schema, Dry::Struct'
  nil
end