Skip to content

Instantly share code, notes, and snippets.

@AMHOL AMHOL/ex.rb
Created Aug 21, 2017

Embed
What would you like to do?
require 'bundler/inline'
gemfile(true) do
source 'https://rubygems.org'
gem 'rom', github: 'rom-rb/rom' do
gem 'rom-repository'
end
gem 'rom-sql', github: 'rom-rb/rom-sql'
gem 'sqlite3'
end
config = ROM::Configuration.new(:sql, 'sqlite::memory')
gateway = config.gateways[:default]
migrations = []
migrations << gateway.migration do
change do
create_table :product do
primary_key :id
column :name, String, null: false
end
end
end
migrations << gateway.migration do
change do
create_table :order_item do
primary_key :id
foreign_key :product_id, :product
column :quantity, Integer, null: false
end
end
end
migrations.each do |migration|
migration.apply(gateway.connection, :up)
end
class Product < ROM::Relation[:sql]
schema(infer: true) do
associations do
has_many :order_items, as: :order_items, relation: :order_item
end
end
end
class OrderItem < ROM::Relation[:sql]
schema(infer: true) do
attribute :id, Types::Int.meta(primary_key: true)
attribute :quantity, Types::Int
attribute :product_id, Types::ForeignKey(:product)
associations do
belongs_to :product, relation: :product
end
end
def by_id(id)
where(id: id)
end
end
config.register_relation(Product)
config.register_relation(OrderItem)
rom = ROM.container(config)
class OrderItemRepository < ROM::Repository[:order_item]
commands :create
relations :product
def [](id)
order_item.by_id(id).one!
end
end
class ProductRepository < ROM::Repository[:product]
commands :create
def [](id)
product.by_id(id).one!
end
end
product_repo = ProductRepository.new(rom)
order_item_repo = OrderItemRepository.new(rom)
product = product_repo.create(name: 'Test')
order_item = order_item_repo.create(product_id: product.id, quantity: 1)
order_item_repo.aggregate(:product).to_a
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.