RDBMS suport for Ruby Object Mapper.
Add this line to your application's Gemfile:
gem 'rom-sql'
And then execute:
$ bundle
Or install it yourself as:
$ gem install rom-sql
ROM uses Sequel under the hood and exposes its Dataset API in relation objects. For schema migrations you can use its Migration API which is available via repositories.
setup = ROM.setup(:sql, "sqlite::memory")
setup.default.connection.create_table(:users) do
primary_key :id
String :name
Boolean :admin
end
setup.default.connection.create_table(:tasks) do
primary_key :id
Integer :user_id
String :title
end
class Users < ROM::Relation[:sql]
base_name :users
def by_name(name)
where(name: name)
end
end
rom = ROM.finalize.env
users = rom.relations.users
tasks = rom.relations.tasks
users.insert(id: 1, name: "Piotr")
tasks.insert(user_id: 1, title: "Be happy")
puts users.by_name("Piotr").with_tasks.to_a.inspect
# => [{:id=>1, :name=>"Piotr", :user_id=>1, :title=>"Be happy"}]
ROM doesn't have a relationship concept like in ActiveRecord or Sequel. Instead it provides a convenient interface for building joined relations that can be mapped to aggregate objects.
There's no lazy-loading, eager-loading or any other magic happening behind the scenes. You're in full control of how data are fetched from the database and it's an explicit operation.
Sequel's association DSL is available in relation definitions which enables
association_join
interface inside relations. To map joined results to
aggregate objects wrap
and group
mapping transformation can be used
ROM.setup(:sql, "sqlite::memory")
class Users < ROM::Relation[:sql]
one_to_many :tasks, key: :user_id
def by_name(name)
where(name: name)
end
def with_tasks
association_join(:tasks, select: [:title])
end
end
class UserMapper < ROM::Mapper
relation :users
model name: 'User'
group tasks: [:title]
end
rom = ROM.finalize.env
users = rom.relations.users
tasks = rom.relations.tasks
users.insert(id: 1, name: "Piotr")
tasks.insert(user_id: 1, title: "Be happy")
rom.read(:users).with_tasks.by_name("Piotr").to_a
# => [#<User:0x007fb31542a098 @id=1, @name="Piotr", @tasks=[{:title=>"Be happy"}]>]
For details please refer to issues.
See LICENSE
file.