Skip to content

Commit

Permalink
feat: Create schema extension on T::Struct (#18)
Browse files Browse the repository at this point in the history
  • Loading branch information
maxveldink authored Feb 27, 2024
1 parent 4d987e7 commit 1f335b7
Show file tree
Hide file tree
Showing 5 changed files with 30 additions and 3 deletions.
3 changes: 2 additions & 1 deletion lib/sorbet-schema.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)
Expand Down
17 changes: 17 additions & 0 deletions lib/sorbet-schema/struct_ext.rb
Original file line number Diff line number Diff line change
@@ -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
2 changes: 2 additions & 0 deletions lib/typed/schema.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
9 changes: 9 additions & 0 deletions test/struct_ext_test.rb
Original file line number Diff line number Diff line change
@@ -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
2 changes: 0 additions & 2 deletions test/support/structs/person.rb
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
# typed: true

require "sorbet-struct-comparable"

class Person < T::Struct
include T::Struct::ActsAsComparable

Expand Down

0 comments on commit 1f335b7

Please sign in to comment.