Skip to content

Commit

Permalink
feat: Add from_hash and from_json helpers to Schemas
Browse files Browse the repository at this point in the history
  • Loading branch information
maxveldink committed Mar 12, 2024
1 parent 366f39e commit 79ea51e
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 3 deletions.
10 changes: 10 additions & 0 deletions lib/typed/schema.rb
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,15 @@ def self.from_struct(struct)
end
)
end

sig { params(hash: Typed::HashSerializer::InputHash).returns(Typed::Serializer::DeserializeResult) }
def from_hash(hash)
Typed::HashSerializer.new(schema: self).deserialize(hash)
end

sig { params(json: String).returns(Typed::Serializer::DeserializeResult) }
def from_json(json)
Typed::JSONSerializer.new(schema: self).deserialize(json)
end
end
end
23 changes: 20 additions & 3 deletions test/typed/schema_test.rb
Original file line number Diff line number Diff line change
@@ -1,16 +1,33 @@
# typed: true

class SchemaTest < Minitest::Test
def test_from_struct_returns_schema
expected_schema = Typed::Schema.new(
def setup
@schema = Typed::Schema.new(
fields: [
Typed::Field.new(name: :name, type: String),
Typed::Field.new(name: :age, type: Integer),
Typed::Field.new(name: :job, type: Job, required: false)
],
target: Person
)
@person = Person.new(name: "Max", age: 29)
end

def test_from_struct_returns_schema
assert_equal(@schema, Typed::Schema.from_struct(Person))
end

def test_from_hash_create_struct
result = @schema.from_hash({name: "Max", age: 29})

assert_success(result)
assert_payload(@person, result)
end

def test_from_json_creates_struct
result = @schema.from_json('{"name": "Max", "age": 29}')

assert_equal(expected_schema, Typed::Schema.from_struct(Person))
assert_success(result)
assert_payload(@person, result)
end
end

0 comments on commit 79ea51e

Please sign in to comment.