Skip to content

Instantly share code, notes, and snippets.

@cflipse
Created December 27, 2019 19:44
Show Gist options
  • Save cflipse/947447e4c656b35d351ffb518df38d65 to your computer and use it in GitHub Desktop.
Save cflipse/947447e4c656b35d351ffb518df38d65 to your computer and use it in GitHub Desktop.
Autostruct repro
#! /usr/bin/env ruby
require 'bundler/inline'
gemfile(true) do
source "https://rubygems.org"
gem 'rom-sql'
gem 'rom-repository'
gem 'sqlite3'
end
config = ROM::Configuration.new(:sql, "sqlite::memory")
gateway = config.gateways[:default]
migration = gateway.migration do
change do
create_table :articles do
primary_key :id
column :title, String, null: false
column :author_id, Integer, null: true
end
create_table :profiles do
primary_key :id
column :name, String, null: false
end
end
end
migration.apply gateway.connection, :up
module Entities
class Profile < ROM::Struct
def first_name
name.split(' ').first
end
end
class Article < ROM::Struct
attribute :author, Entities::Profile
end
end
class ProfilesRelation < ROM::Relation[:sql]
struct_namespace Entities
schema(:profiles, infer: true)
end
class ArticlesRelation < ROM::Relation[:sql]
struct_namespace Entities
schema(:articles, infer: true) do
associations do
belongs_to :profiles, as: :author, foreign_key: :author_id, relation: :profiles
end
end
end
config.register_relation(ProfilesRelation)
config.register_relation(ArticlesRelation)
rom = ROM.container(config)
class Articles < ROM::Repository[:articles]
def list
articles.combine(:author)
end
end
jdoe = rom.relations[:profiles].command(:create).call(name: "John Doe")
rom.relations[:articles].command(:create).call(title: "testing", author_id: jdoe[:id])
articles = Articles.new(rom)
article = articles.list.first
# I expect article.author to be an Entities::Profile
pp article
puts article.author.first_name
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment