Created
March 5, 2015 16:01
-
-
Save schmurfy/babde8badfb3cf551c7a to your computer and use it in GitHub Desktop.
rom tinkering
This file contains 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
require 'rubygems' | |
require 'bundler/setup' | |
require 'rom' | |
require 'rom/memory' | |
require 'rom/sql' | |
sql = ROM.setup(:sql, "sqlite:memory") | |
sql.default.connection.create_table(:animals) do | |
primary_key :id | |
Integer :user_id | |
String :name | |
String :type | |
end | |
class Animals < ROM::Relation[:sql] | |
def owned_by(id) | |
where(user_id: id) | |
end | |
end | |
class CreateAnimal < ROM::Commands::Create[:sql] | |
register_as :create | |
relation :animals | |
result :one | |
end | |
ROM.setup(:memory) | |
# This is our domain-specific class | |
class User | |
attr_reader :id, :name, :age | |
def initialize(attributes) | |
@id, @name, @age = attributes.values_at(:id, :name, :age) | |
end | |
end | |
# Here we define user relation which encapsulates accessing user data that | |
# we can map to domain objects | |
class Users < ROM::Relation[:memory] | |
def by_name(name) | |
restrict(name: name) | |
end | |
def adults | |
restrict { |user| user[:age] >= 18 } | |
end | |
end | |
# Even though mappers can be derived from model definitions here's how you | |
# could define it explicitly | |
class UserMapper < ROM::Mapper | |
relation :users | |
register_as :entity | |
model User | |
attribute :name | |
attribute :age | |
end | |
# You can define specialized commands that handle creating, updating and deleting | |
# data, those classes can use external input param handlers and validators too | |
class CreateUser < ROM::Commands::Create[:memory] | |
register_as :create | |
relation :users | |
result :one | |
end | |
# finalize the setup and retrieve object registry (aka ROM env) | |
rom = ROM.finalize.env | |
# accessing defined commands | |
rom.command(:users).create.call(id: 1, name: "Joe", age: 17) | |
rom.command(:users).create.call(id: 2, name: "Jane", age: 18) | |
rom.command(:users).create.call(id: 3, name: "Jane", age: 11) | |
rom.command(:animals).create.call(type: 'cat', name: 'feather', user_id: 1) | |
# reading relations using defined mappers | |
p rom.relation(:users) { |r| r.by_name("Jane").adults }.as(:entity).to_a | |
p rom.relation(:users) { |r| r.by_name("Jane") }.as(:entity).to_a |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment