Sha256: ec6059e06029f71e6c424bcefbc948acd107f536bc659aa793019d8ffb820609

Contents?: true

Size: 1.43 KB

Versions: 32

Compression:

Stored size: 1.43 KB

Contents

require "yaml"

module Lutaml
  module Model
    module Schema
      class YamlSchema
        def self.generate(klass, options = {})
          schema = generate_schema(klass)
          options[:pretty] ? schema.to_yaml : YAML.dump(schema)
        end

        def self.generate_schema(klass)
          {
            "type" => "map",
            "mapping" => generate_mapping(klass),
          }
        end

        def self.generate_mapping(klass)
          klass.attributes.each_with_object({}) do |(name, attr), mapping|
            mapping[name.to_s] = generate_attribute_schema(attr)
          end
        end

        def self.generate_attribute_schema(attr)
          if attr.type <= Lutaml::Model::Serialize
            generate_schema(attr.type)
          elsif attr.collection?
            {
              "type" => "seq",
              "sequence" => [{ "type" => get_yaml_type(attr.type) }],
            }
          else
            { "type" => get_yaml_type(attr.type) }
          end
        end

        def self.get_yaml_type(type)
          {
            Lutaml::Model::Type::String => "str",
            Lutaml::Model::Type::Integer => "int",
            Lutaml::Model::Type::Boolean => "bool",
            Lutaml::Model::Type::Float => "float",
            Lutaml::Model::Type::Decimal => "float",
            Lutaml::Model::Type::Hash => "map",
          }[type] || "str" # Default to string for unknown types
        end
      end
    end
  end
end

Version data entries

32 entries across 32 versions & 1 rubygems

Version Path
lutaml-model-0.5.3 lib/lutaml/model/schema/yaml_schema.rb
lutaml-model-0.5.2 lib/lutaml/model/schema/yaml_schema.rb
lutaml-model-0.5.1 lib/lutaml/model/schema/yaml_schema.rb
lutaml-model-0.5.0 lib/lutaml/model/schema/yaml_schema.rb
lutaml-model-0.4.0 lib/lutaml/model/schema/yaml_schema.rb
lutaml-model-0.3.30 lib/lutaml/model/schema/yaml_schema.rb
lutaml-model-0.3.29 lib/lutaml/model/schema/yaml_schema.rb
lutaml-model-0.3.28 lib/lutaml/model/schema/yaml_schema.rb
lutaml-model-0.3.27 lib/lutaml/model/schema/yaml_schema.rb
lutaml-model-0.3.26 lib/lutaml/model/schema/yaml_schema.rb
lutaml-model-0.3.25 lib/lutaml/model/schema/yaml_schema.rb
lutaml-model-0.3.24 lib/lutaml/model/schema/yaml_schema.rb
lutaml-model-0.3.23 lib/lutaml/model/schema/yaml_schema.rb
lutaml-model-0.3.22 lib/lutaml/model/schema/yaml_schema.rb
lutaml-model-0.3.21 lib/lutaml/model/schema/yaml_schema.rb
lutaml-model-0.3.20 lib/lutaml/model/schema/yaml_schema.rb
lutaml-model-0.3.19 lib/lutaml/model/schema/yaml_schema.rb
lutaml-model-0.3.18 lib/lutaml/model/schema/yaml_schema.rb
lutaml-model-0.3.17 lib/lutaml/model/schema/yaml_schema.rb
lutaml-model-0.3.16 lib/lutaml/model/schema/yaml_schema.rb