diff --git a/lib/sorbet-schema.rb b/lib/sorbet-schema.rb index 8c36ac0..b9984c9 100644 --- a/lib/sorbet-schema.rb +++ b/lib/sorbet-schema.rb @@ -10,7 +10,7 @@ loader = Zeitwerk::Loader.new loader.push_dir(__dir__.to_s) loader.ignore(__FILE__) -loader.ignore("#{__dir__}/sorbet-schema/*.rb") +loader.ignore("#{__dir__}/sorbet-schema/**/*.rb") loader.inflector.inflect( "json_serializer" => "JSONSerializer" ) @@ -21,6 +21,12 @@ # but contains extensions, so we need to manually require it. require_relative "sorbet-schema/hash_transformer" +# We want to add a default `schema` method to structs +# that will guarentee a schema can be created for use +# with serialization. This can (and should) be overridden +# in child struct classes. +require_relative "sorbet-schema/t/struct" + # Sorbet-aware namespace to super-charge your projects module Typed Value = T.type_alias { T.untyped } diff --git a/lib/sorbet-schema/t/struct.rb b/lib/sorbet-schema/t/struct.rb new file mode 100644 index 0000000..351f045 --- /dev/null +++ b/lib/sorbet-schema/t/struct.rb @@ -0,0 +1,12 @@ +# typed: strict + +module T + class Struct + extend T::Sig + + sig { overridable.returns(Typed::Schema) } + def self.schema + Typed::Schema.from_struct(self) + end + end +end diff --git a/test/t/struct_test.rb b/test/t/struct_test.rb new file mode 100644 index 0000000..bd7af05 --- /dev/null +++ b/test/t/struct_test.rb @@ -0,0 +1,15 @@ +# typed: true + +class StructTest < Minitest::Test + def test_schema_can_be_derived_from_struct + expected_schema = Typed::Schema.new( + fields: [ + Typed::Field.new(name: :name, type: String), + Typed::Field.new(name: :capital, type: T::Utils.coerce(T::Boolean)) + ], + target: City + ) + + assert_equal(expected_schema, City.schema) + end +end