Created
February 13, 2017 22:43
-
-
Save Kukunin/186e7af66c4be0d720b617a2084e441e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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' | |
end | |
require 'rspec/autorun' | |
describe ROM::Repository do | |
let(:rom) { ROM.container(configuration) } | |
let(:configuration) do | |
ROM::Configuration.new(:sql, 'sqlite::memory').tap do |config| | |
config.default.create_table(:users) do | |
primary_key :id | |
column :name, String, null: false | |
end | |
config.default.create_table(:posts) do | |
primary_key :id | |
foreign_key :user_id, :users, null: false | |
column :title, String, null: false | |
end | |
config.relation(:users) do | |
schema(infer: true) | |
view(:for_posts, schema) do |posts| | |
where(id: posts.pluck(:user_id)) | |
end | |
end | |
end | |
end | |
let(:repo) do | |
Class.new(ROM::Repository[:posts]) do | |
relations :users | |
def all | |
posts.combine(one: {user: [users.for_posts, user_id: :id]}) | |
end | |
end.new(rom) | |
end | |
before { create_post(title: 'post_title', user_name: 'Sergiy') } | |
it 'contains 1 user' do | |
expect(repo.users.count).to eq 1 | |
end | |
it 'contains 1 post' do | |
expect(repo.posts.count).to eq 1 | |
end | |
let(:first) { repo.all.limit(1).one } | |
it 'combines posts with users' do | |
expect(first.user.name).to eq 'Sergiy' | |
end | |
def create_post(attrs) | |
user_id = rom.relations[:users].insert(name: attrs.fetch(:user_name)) | |
rom.relations[:posts].insert(title: attrs.fetch(:title), user_id: user_id) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
first.to_h
returns{:id=>1, :user_id=>1, :title=>"post_title", :user=>{}}