Skip to content

Instantly share code, notes, and snippets.

@solnic
Last active February 4, 2017 10:32
Show Gist options
  • Save solnic/3b68342482cf1414f719 to your computer and use it in GitHub Desktop.
Save solnic/3b68342482cf1414f719 to your computer and use it in GitHub Desktop.
require 'rom'
require 'rom-rails'
`rm -Rf /tmp/romtest.sqlite`
ROM.setup(:sql, 'sqlite:///tmp/romtest.sqlite')
class Events < ROM::Relation[:sql]
end
class Organisers < ROM::Relation[:sql]
end
class CreateEvent < ROM::Commands::Create[:sql]
class Attributes
include ROM::Model::Attributes
attribute :name
attribute :organiser_id
end
relation :events
register_as :create
result :one
associates :organiser, key: [:organiser_id, :id]
input Attributes
end
class CreateOrganiser < ROM::Commands::Create[:sql]
class Attributes
include ROM::Model::Attributes
attribute :email
end
relation :organisers
register_as :create
result :one
input Attributes
end
class InputMapper < ROM::Mapper
reject_keys true
wrap :organiser do
attribute :email
wrap :event do
attribute :name, from: :event_name
end
end
def call(input)
super([input]).first
end
end
class Validator
include ROM::Model::Validator
validates :event_name, presence: true
end
ROM.finalize
rom = ROM.env
gateway = rom.gateways.fetch(:default)
migration = gateway.migration do
change do
create_table :organisers do
primary_key :id
column :email, String, null: false
end
create_table :events do
primary_key :id
column :name, String, null: false
column :organiser_id, Integer, null: false
end
end
end
migration.apply(gateway.connection, :up)
command = rom.command([
{ organiser: :organisers }, [:create, [
{ event: :events }, [:create]
]]
])
input = {
email: 'test@example.com',
event_name: 'Test Event'
}
mapper = InputMapper.build
validator = Validator.new(input)
if validator.valid?
result = command.call(mapper.call(input))
puts result
# {:id=>1, :email=>"test@example.com"}
# {:id=>1, :name=>"Test Event", :organiser_id=>1}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment