Skip to content

Instantly share code, notes, and snippets.

@szabba
Last active November 18, 2015 18:22
Show Gist options
  • Save szabba/29ee106bdf9bdaf45f62 to your computer and use it in GitHub Desktop.
Save szabba/29ee106bdf9bdaf45f62 to your computer and use it in GitHub Desktop.
module Result
def Result.capture
begin
Ok.new(yield)
rescue StandardError => e
Error.new(e)
end
end
end
module ResultMethods
def map
handle_result(
Proc.new {|val| Ok.new(yield(val)) },
Proc.new {|err| self })
end
def join
handle_result(
Proc.new {|val| val },
Proc.new {|err| self })
end
def flat_map
map {|x| yield(x) }.join
end
def map_safe
handle_result(
Proc.new {|val| Result::capture { yield(val) } },
Proc.new {|err| self })
end
def flat_map_safe
map_safe {|x| yield(x) }.join
end
end
class Ok
include ResultMethods
def initialize(result)
@result = result
end
def to_s
"Ok.new(#{@result.to_s})"
end
def handle_result(success_handler, failure_handler)
success_handler.call(@result)
end
end
class Error
include ResultMethods
def initialize(err)
@err = err
end
def to_s
"Error.new(#{@err.to_s})"
end
def handle_result(success_handler, failure_handler)
failure_handler.call(@err)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment