rom-rb / rom

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

Cannot get struct_namespace to work within a repository #544

Closed janko closed 5 years ago

janko commented 5 years ago

Describe the bug

I'm using struct_namespace in a relation, which is applied when I use the relation directly, but isn't within a repository. I believe this is a bug, because the relation object within the repository shows the correct struct_namespace.

To Reproduce

require "rom"

module Entities
  class User < ROM::Struct
  end
end

rom = ROM.container(:sql, "sqlite::memory") do |config|
  config.default.create_table(:users) do
    primary_key :id
  end

  config.relation(:users) do
    schema(infer: true)
    struct_namespace Entities
    auto_struct true
  end
end

class UserRepo < ROM::Repository[:users]
  commands :create

  def by_id(id)
    users.by_pk(id).one!
  end
end

user_repo = UserRepo.new(rom)
p user_repo.create({})
# => #<ROM::Struct::User id=1>

p user_repo.by_id(1)
# => #<ROM::Struct::User id=1>

p rom.relations[:users].by_pk(1).one!
# => #<Entities::User id=1>
p user_repo.users.class.struct_namespace
# => Entities

Expected behavior

I expected UserRepo#by_id to return an Entities::User object, especially because the UserRepo#users relation object seems to have the correct struct_namespace configured. I get an Entities::User when I access the relation directly, but not through the repository.

I would ideally like if UserRepo#create also respected struct_namespace, though I get that commands might not even go through relation objects.

Your environment

janko commented 5 years ago

I found the answer on the website:

Screenshot 2019-06-01 at 20 27 48

Setting struct_namespace on the repository indeed works as expected. It would be convenient if struct_namespace setting from the relation would extend to the repository as well, but that's something that can be discussed outside of GitHub issues.

solnic commented 5 years ago

@janko I think you're right and repos should respect relation setting but only if it's set to something, otherwise repo setting should override whatever relation used.