Skip to content

Instantly share code, notes, and snippets.

@jmcervera
Created February 7, 2017 20:08
Show Gist options
  • Save jmcervera/7dcf203b5170c39a62f137e4da732794 to your computer and use it in GitHub Desktop.
Save jmcervera/7dcf203b5170c39a62f137e4da732794 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require "rom-sql"
require "rom-repository"
require "byebug"
module Persistence
module Relations
class Configurations < ROM::Relation[:sql]
gateway :alternate
schema(:bns_configurations, infer: true, as: :configurations) do
associations do
has_many :parameters
end
end
end
class Parameters < ROM::Relation[:sql]
gateway :alternate
schema(:bns_parameters, infer: true, as: :parameters) do
associations do
belongs_to :configuration
end
end
end
end
end
module Repositories
class Configurations < ROM::Repository[:configurations]
commands :create, update: :by_pk
relations :parameters
def by_id(id)
aggregate(:parameters).by_pk(id).one!
end
end
end
config = ROM::Configuration.new(default: [:sql, "sqlite::memory"],
alternate: [:sql, "postgres://localhost:5432/rom_sql"])
config.gateways[:alternate].tap do |gateway|
migration1 = gateway.migration do
change do
create_table :bns_configurations do
primary_key :id
column :description, String, null: false
end
end
end
migration2 = gateway.migration do
change do
create_table :bns_parameters do
primary_key :id
column :configuration_id, Integer, null: false
column :description, String, null: false
column :value, Integer, null: false
index :configuration_id
end
end
end
migration1.apply gateway.connection, :up
migration2.apply gateway.connection, :up
end
config.register_relation Persistence::Relations::Configurations
config.register_relation Persistence::Relations::Parameters
container = ROM.container(config)
puts container.relations[:configurations].class.dataset # => bns_configurations
puts container.relations[:parameters].class.dataset # => bns_parameters
repo = Repositories::Configurations.new(container)
repo.create(description: 'test')
data = repo.by_id(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment