Last active
February 4, 2017 10:32
-
-
Save solnic/3b68342482cf1414f719 to your computer and use it in GitHub Desktop.
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 '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: '[email protected]', | |
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=>"[email protected]"} | |
# {: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