Skip to content

Commit

Permalink
feat: Add schema method to structs (#60)
Browse files Browse the repository at this point in the history
  • Loading branch information
maxveldink authored Mar 30, 2024
1 parent e90d62b commit 4b7ff34
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 1 deletion.
8 changes: 7 additions & 1 deletion lib/sorbet-schema.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)
Expand All @@ -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 }
Expand Down
12 changes: 12 additions & 0 deletions lib/sorbet-schema/t/struct.rb
Original file line number Diff line number Diff line change
@@ -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
15 changes: 15 additions & 0 deletions test/t/struct_test.rb
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit 4b7ff34

Please sign in to comment.