Skip to content

Conversation

baweaver
Copy link

Fix JSON schema generation for Dry::Struct wrapped in constructors

Fixes #495

Problem

When generating JSON schema for a schema containing a Dry::Struct wrapped in a constructor (e.g.,
Address.constructor(&:itself)), all struct properties were omitted from the generated schema, returning only
{type: "object"} instead of the full schema with properties.

Root Cause

The struct? method in the struct extension only recognized direct struct classes (Class instances that inherit
from Dry::Struct), but not struct constructors (Dry::Types::Constructor instances wrapping structs).

Solution

• Extended struct? method to also recognize Dry::Types::Constructor instances that wrap struct classes
• Added extract_struct_class method to extract the underlying struct class from both direct structs and
constructors
• Modified the macro processing to use the extracted struct class for schema compilation

Changes

lib/dry/schema/extensions/struct.rb: Enhanced struct detection and extraction logic
spec/integration/extensions/json_schema/struct_constructor_spec.rb: Comprehensive test coverage
CHANGELOG.md: Document the fix

Before/After

# Before: Missing struct properties
Dry::Schema.Params do 
  required(:address).value(Address.constructor(&:itself)) 
end.json_schema
# => {:properties=>{:address=>{:type=>"object"}}} # No properties

# After: Full struct schema included  
Dry::Schema.Params do 
  required(:address).value(Address.constructor(&:itself)) 
end.json_schema
# => {:properties=>{:address=>{:type=>"object", :properties=>{:street=>{...}}}}} # Properties included

Testing

• Tests direct struct usage (still works)
• Tests struct constructor usage (now works)
• Verifies both generate schemas with proper struct properties

- Extend struct? method to recognize struct constructors
- Add extract_struct_class method to handle both direct structs and constructors
- Ensure struct properties are included in JSON schema for constructor-wrapped structs
- Add comprehensive tests for struct constructor JSON schema generation

Fixes dry-rb#495
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.

json_schema fails on a Dry::Struct wrapped in a constructor
1 participant