rom-rb / rom

Data mapping and persistence toolkit for Ruby
https://rom-rb.org
MIT License
2.07k stars 161 forks source link

Broken example code, unexpected auto_struct behavior #685

Closed pboling closed 1 week ago

pboling commented 1 year ago

Describe the bug

I made a script of the example code, and it seems that the example code for the auto-generated structs no longer reflects reality, and as a result I am very confused about how to setup my custom name-spaced structs, when not even the auto-generated ones work as expected.

The example code I mostly copied is here: https://api.rom-rb.org/rom/ROM/Struct Note that as written the example code doesn't work at all, as it was missing the conf.relation(:users), so I added that. Even with that, the example code still doesn't work at all, and raises the error: undefined method 'schema' for ROM::OpenStruct:Class (NoMethodError)

To Reproduce

require 'bundler/inline'

gemfile do
  source 'https://rubygems.org'
  gem 'rom'
  gem 'rom-sql'
  gem 'sqlite3'
end

rom = ROM.container(:sql, 'sqlite::memory') do |conf|
  conf.default.create_table(:users) do
    primary_key :id
    column :name, String
  end

  conf.relation(:users) do
  end
end

class UserRepo < ROM::Repository[:users]
end

user_repo = UserRepo.new(rom)

# get auto-generated User struct
model = user_repo.users.mapper.model

puts "model: #{model}"
# EXPECTED
# model: ROM::Struct::User
#
# ACTUAL
# model: ROM::OpenStruct

puts model.schema.key(:id)
# EXPECTED:
# #<Dry::Types[id: Nominal<Integer meta={primary_key: true, source: :users}>]>
#
# ACTUAL:
# undefined method `schema' for ROM::OpenStruct:Class (NoMethodError)

My environment

cllns commented 3 weeks ago

I know this is a year old but if you change:

  conf.relation(:users) do
  end

to

  conf.relation(:users) do
    schema(infer: true)
    auto_struct true
  end

then it works as desired.

The reason is: "ROM's open structs are used for relations with empty schemas"

Ahmadtaha1122 commented 2 weeks ago

👍

pboling commented 1 week ago

Closing. This was a problem of documentation and is fixed in the main branch.