Skip to content

Commit

Permalink
feat: Add Schema#add_serializer to easily update serializer
Browse files Browse the repository at this point in the history
  • Loading branch information
maxveldink committed Mar 21, 2024
1 parent d160a26 commit 1850f7d
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
14 changes: 14 additions & 0 deletions lib/typed/schema.rb
Original file line number Diff line number Diff line change
Expand Up @@ -27,5 +27,19 @@ def from_hash(hash)
def from_json(json)
Typed::JSONSerializer.new(schema: self).deserialize(json)
end

sig { params(field_name: Symbol, serializer: Field::InlineSerializer).returns(Schema) }
def add_serializer(field_name, serializer)
self.class.new(
target: target,
fields: fields.map do |field|
if field.name == field_name
Field.new(name: field.name, type: field.type, required: field.required, inline_serializer: serializer)
else
field
end
end
)
end
end
end
12 changes: 12 additions & 0 deletions test/typed/schema_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,16 @@ def test_from_json_creates_struct
assert_success(result)
assert_payload(MAX_PERSON, result)
end

def test_add_serializer_when_no_matching_field_returns_same_schema
schema = @schema.add_serializer(:not_here, ->(value) { value + "a" })

assert_equal(@schema, schema)
end

def test_add_serializer_when_matching_field_returns_schema_with_serializer
schema = @schema.add_serializer(:name, ->(value) { value + "a" })

refute_equal(@schema, schema)
end
end

0 comments on commit 1850f7d

Please sign in to comment.