Skip to content

Instantly share code, notes, and snippets.

@schmurfy
Created March 5, 2015 16:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save schmurfy/babde8badfb3cf551c7a to your computer and use it in GitHub Desktop.
Save schmurfy/babde8badfb3cf551c7a to your computer and use it in GitHub Desktop.
rom tinkering
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