Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save flash-gordon/9ce0e42967641efd425df99a1eb90350 to your computer and use it in GitHub Desktop.
Save flash-gordon/9ce0e42967641efd425df99a1eb90350 to your computer and use it in GitHub Desktop.
Example of reading aggregates in rom-rb
begin
require 'bundler/inline'
rescue LoadError => e
$stderr.puts 'Bundler version 1.10 or later is required.'
raise e
end
gemfile(true) do
source 'https://rubygems.org'
gem 'rom'
gem 'rom-sql'
gem 'rom-repository'
gem 'sqlite3'
gem 'rspec'
gem 'pry'
gem 'pg'
end
require 'rspec/autorun'
describe ROM::Repository do
let(:rom) { ROM.container(configuration) }
let(:configuration) do
ROM::Configuration.new(:sql, 'postgres://localhost:5432/rom_repository').tap do |config|
config.gateways[:default].connection.drop_table?(:tags)
config.gateways[:default].connection.drop_table?(:posts)
config.default.create_table(:posts) do
primary_key :id
column :title, String, null: false
end
config.default.create_table(:tags) do
primary_key :id
foreign_key :post_id, :posts, null: false
column :name, String, null: false
end
config.relation(:posts) do
schema(infer: true) do
associations do
has_many :tags
end
end
view :with_tags do
schema do
posts = relations[:posts].qualified
tags = relations[:tags].qualified
new([
posts[:id],
posts[:title],
*tags.project { array::array_agg(tags[:name]).as(:tag_names) }.schema
])
end
relation do
join(tags).group(self[:id].qualified)
end
end
end
end
end
let(:repo) do
Class.new(ROM::Repository[:posts]) do
relations :tags
end.new(rom)
end
let(:post_id) { repo.root.insert(title: 'post 1') }
let(:posts) { repo.root.with_tags.to_a }
before { repo.tags.insert(post_id: post_id, name: 'tag 1') }
before { repo.tags.insert(post_id: post_id, name: 'tag 2') }
it { expect(posts.count).to eq 1 }
it { expect(posts.first.title).to eq 'post 1' }
it { expect(posts.first.tag_names).to eq ['tag 1', 'tag 2'] }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment