Skip to content

Instantly share code, notes, and snippets.

@flash-gordon
Created February 13, 2017 14:25
Show Gist options
  • Save flash-gordon/0cea91892f7d853dd2f5af8434c0b889 to your computer and use it in GitHub Desktop.
Save flash-gordon/0cea91892f7d853dd2f5af8434c0b889 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require "bundler/setup"
require "rom-repository"
config = ROM::Configuration.new(:sql, 'postgres://localhost/rom_repository')
config.relation(:books) do
schema(:books) do
attribute :id, ROM::SQL::Types::Serial
attribute :title, ROM::SQL::Types::String
attribute :created_at, ROM::SQL::Types::Time
attribute :updated_at, ROM::SQL::Types::Time
end
end
config.relation(:users) do
schema(infer: true) do
attribute :name, ROM::SQL::Types::Symbol.meta(read: ROM::SQL::Types::Symbol.constructor(&:to_sym))
associations do
has_many :tasks
end
end
def by_id(id)
where(id: id)
end
def all
select(:id, :name).order(:name, :id)
end
def find(criteria)
where(criteria)
end
end
config.relation(:tasks) do
schema(infer: true) do
associations do
belongs_to :user
end
end
def find(criteria)
where(criteria)
end
def for_users(users)
where(user_id: users.map { |u| u[:id] })
end
end
config.relation(:tags)
rom = ROM.container(config)
repo = Class.new(ROM::Repository[:users]) {
commands :create, update: :by_pk, delete: :by_pk
relations :tasks, :tags, :books
}.new(rom)
require "pry"
binding.pry
# [2] pry(main)> repo.users.to_arepo.users.to_a
# => [#<ROM::Struct[User] name=:Jane id=1>, #<ROM::Struct[User] name=:Albert id=2>, #<ROM::Struct[User] name=:Albert id=4>]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment