Skip to content

Fix BaseModel nested model coercion#295

Open
bjedrocha wants to merge 1 commit into
openai:mainfrom
bjedrocha:fix/base-model-nested-coercion
Open

Fix BaseModel nested model coercion#295
bjedrocha wants to merge 1 commit into
openai:mainfrom
bjedrocha:fix/base-model-nested-coercion

Conversation

@bjedrocha

Copy link
Copy Markdown

Summary

Fixes nested BaseModel coercion so generated setters store successfully coerced nested model values instead of preserving the original raw hashes/arrays.

Details

Previously, the generated BaseModel setter computed coerced nested model values but stored the original raw input while marking the field as successfully coerced. As a result, nested BaseModel and ArrayOf[BaseModel] fields initialized from hashes could remain plain Hash values.

This updates the setter success check to store the coerced value when coercion succeeds, while preserving existing behaviour for already-correct values and failed conversions.

Before / after

require "openai"

class Item < OpenAI::BaseModel
  required :name, String
end

class Container < OpenAI::BaseModel
  optional :item, Item
  optional :items, OpenAI::ArrayOf[Item]
end

container = Container.new(
  item: { name: "single" },
  items: [{ name: "array" }]
)

Before this fix, the setter computed the coerced Item values but stored the raw input:

container.item.class
# => Hash

container.items.first.class
# => Hash

container.item.name
# => NoMethodError: undefined method `name' for an instance of Hash

After this fix, successful coercion is stored:

container.item.class
# => Item

container.items.first.class
# => Item

container.item.name
# => "single"

container.items.first.name
# => "array"

Store coerced nested model values during BaseModel construction and assignment
instead of preserving raw hashes. Add coverage for nested model fields and arrays.
@bjedrocha bjedrocha requested a review from a team as a code owner July 5, 2026 02:31
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant