Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add schema method to structs #60

Merged
merged 1 commit into from
Mar 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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