Created
December 2, 2014 11:01
-
-
Save solnic/53734eba5d6007247d0f to your computer and use it in GitHub Desktop.
kleisli-inspired spike for handling inserts with associations in rom-rb
This file contains hidden or 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
class Result | |
attr_reader :value, :error | |
class Success < Result | |
def initialize(value) | |
@value = value | |
end | |
def >(f) | |
f.call(value) | |
end | |
end | |
class Failure < Result | |
def initialize(error) | |
@error = error | |
end | |
def >(&f) | |
self | |
end | |
end | |
end | |
def try(&f) | |
Result::Success.new(f.call) | |
rescue => e | |
Result::Failure.new(e) | |
end | |
describe 'try' do | |
it 'somehow works' do | |
input = { name: 'Piotr', tasks: [ { title: 'First' }, { title: 'Second' } ] } | |
insert_user = Proc.new do |user| | |
user.merge(id: 1) | |
end | |
insert_task = Proc.new do |task, user| | |
task.merge(user_id: user.fetch(:id)) | |
end | |
insert_tasks = Proc.new do |tasks, user| | |
tasks.map { |task| insert_task[task, user] } | |
end.curry[input[:tasks]] | |
result = try { | |
insert_user[input] | |
} >-> user { | |
try { | |
insert_tasks[user] | |
} | |
} | |
expect(result.value).to eql( | |
[{ user_id: 1, title: 'First' }, { user_id: 1, title: 'Second' }] | |
) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
oh my