From 1f335b7746199034208df8b5718edae73b4158dd Mon Sep 17 00:00:00 2001 From: Max VelDink Date: Tue, 27 Feb 2024 14:06:40 -0500 Subject: [PATCH] feat: Create schema extension on `T::Struct` (#18) --- lib/sorbet-schema.rb | 3 ++- lib/sorbet-schema/struct_ext.rb | 17 +++++++++++++++++ lib/typed/schema.rb | 2 ++ test/struct_ext_test.rb | 9 +++++++++ test/support/structs/person.rb | 2 -- 5 files changed, 30 insertions(+), 3 deletions(-) create mode 100644 lib/sorbet-schema/struct_ext.rb create mode 100644 test/struct_ext_test.rb diff --git a/lib/sorbet-schema.rb b/lib/sorbet-schema.rb index a9367fe..93e9696 100644 --- a/lib/sorbet-schema.rb +++ b/lib/sorbet-schema.rb @@ -3,13 +3,14 @@ require "sorbet-runtime" require "sorbet-result" +require "sorbet-struct-comparable" # We can't use `Loader.for_gem` here as we've unconventionally named the root file. require "zeitwerk" loader = Zeitwerk::Loader.new loader.push_dir(__dir__.to_s) loader.ignore(__FILE__) -loader.ignore("#{__dir__}/sorbet-schema/version.rb") +loader.ignore("#{__dir__}/sorbet-schema/*.rb") loader.inflector.inflect( "json_serializer" => "JSONSerializer" ) diff --git a/lib/sorbet-schema/struct_ext.rb b/lib/sorbet-schema/struct_ext.rb new file mode 100644 index 0000000..645b027 --- /dev/null +++ b/lib/sorbet-schema/struct_ext.rb @@ -0,0 +1,17 @@ +# typed: strict + +module T + class Struct + extend T::Sig + + sig { returns(Typed::Schema) } + def self.create_schema + Typed::Schema.new( + target: self, + fields: props.map do |name, properties| + Typed::Field.new(name:, type: properties[:type], required: !properties[:fully_optional]) + end + ) + end + end +end diff --git a/lib/typed/schema.rb b/lib/typed/schema.rb index 44b1d0d..53bdb17 100644 --- a/lib/typed/schema.rb +++ b/lib/typed/schema.rb @@ -4,6 +4,8 @@ module Typed class Schema < T::Struct extend T::Sig + include T::Struct::ActsAsComparable + const :fields, T::Array[Field], default: [] const :target, T.class_of(T::Struct) diff --git a/test/struct_ext_test.rb b/test/struct_ext_test.rb new file mode 100644 index 0000000..f83b30d --- /dev/null +++ b/test/struct_ext_test.rb @@ -0,0 +1,9 @@ +# typed: true + +require "sorbet-schema/struct_ext" + +class StructExtTest < Minitest::Test + def test_create_schema_is_available + assert_equal(PersonSchema, Person.create_schema) + end +end diff --git a/test/support/structs/person.rb b/test/support/structs/person.rb index e27ab61..ecc3013 100644 --- a/test/support/structs/person.rb +++ b/test/support/structs/person.rb @@ -1,7 +1,5 @@ # typed: true -require "sorbet-struct-comparable" - class Person < T::Struct include T::Struct::ActsAsComparable