Skip to content

Instantly share code, notes, and snippets.

@solnic
Created December 2, 2014 11:01
Show Gist options
  • Save solnic/53734eba5d6007247d0f to your computer and use it in GitHub Desktop.
Save solnic/53734eba5d6007247d0f to your computer and use it in GitHub Desktop.
kleisli-inspired spike for handling inserts with associations in rom-rb
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
@rkh
Copy link

rkh commented Dec 2, 2014

oh my

@solnic
Copy link
Author

solnic commented Dec 2, 2014

😱 I know ;)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment