Skip to content
Open
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
11 changes: 7 additions & 4 deletions lib/openai/internal/type/base_model.rb
Original file line number Diff line number Diff line change
Expand Up @@ -83,12 +83,15 @@ def fields
target = type_fn.call
state = OpenAI::Internal::Type::Converter.new_coerce_state(translate_names: false)
coerced = OpenAI::Internal::Type::Converter.coerce(target, value, state: state)
error = @coerced.store(name_sym, state.fetch(:error) || true)
status = state.fetch(:error) || true
@coerced.store(name_sym, status)
stored =
case [target, error]
in [OpenAI::Internal::Type::Converter | Symbol, nil]
case [target, status, value]
in [OpenAI::Internal::Type::Converter | Symbol, true, ^target]
value
in [OpenAI::Internal::Type::Converter | Symbol, true, _]
coerced
else
else # rubocop:disable Lint/DuplicateBranch
value
end
@data.store(name_sym, stored)
Expand Down
26 changes: 26 additions & 0 deletions test/openai/internal/type/base_model_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -345,6 +345,15 @@ class M6 < M1
optional :b, M6
end

class M7 < OpenAI::Internal::Type::BaseModel
required :a, Integer
end

class M8 < OpenAI::Internal::Type::BaseModel
optional :item, M7
optional :items, OpenAI::Internal::Type::ArrayOf[M7]
end

def test_coerce
cases = {
[M1, {}] => [{yes: 1, no: 1}, {}],
Expand Down Expand Up @@ -448,6 +457,23 @@ def test_accessors
end
end

def test_constructor_stores_coerced_nested_models
model = M8.new(item: {a: 1}, items: [{a: 2}])

assert_instance_of(M7, model.item)
assert_instance_of(M7, model.items.fetch(0))
assert_instance_of(M7, model.to_h.fetch(:item))
assert_instance_of(M7, model.to_h.fetch(:items).fetch(0))

model.item = {a: 3}
model.items = [{a: 4}]

assert_instance_of(M7, model.item)
assert_instance_of(M7, model.items.fetch(0))
assert_instance_of(M7, model.to_h.fetch(:item))
assert_instance_of(M7, model.to_h.fetch(:items).fetch(0))
end

def test_inplace_modification
m1 = M6.new(a: [])
m1.a << M6.new(a: [])
Expand Down