Result
Installation
Add this line to your application's Gemfile:
gem 'result-monad'
And then execute:
$ bundle
Or install it yourself as:
$ gem install result-monad
Usage
Use of the Result Monad is a paradigm that is baked into Rust and can lead to very good error handling. This is an
initial design, and will need to be refined. The Capture()
constructor makes it quite easy to integrate Result into
a preexisting code base.
Examples
Capture
success into an Ok result, and exceptions into an Error result via
Capture { 100 / 10 } #=> Result<Ok(10)>
Capture { 100 / 0 } #=> Result<Error(divided by 0)>
Construct Ok or Error yourself
def can_go_wrong
res = do_operation
if res.meets_expectations
Ok(res)
else
Error(res)
end
end
Basic Dichotomy
def divide(x, y)
Capture { x / y }
end
x = divide 50, 10 #=> Result<Ok(5)>
x.ok? #=> true
x.error? #=> false
y = divide 50, 0 #=> Result<Error(divided by 0)>
y.error? #=> true
y.ok? #=> false
Chaining computations with map
x = Ok(100)
x.map {|i| i / 10}
.map {|i| i / 5}
.map {|i| i / 1}
#=> Result<Ok(2)>
Carrying errors through computations
x = Ok(100)
x.map {|i| i / 10}
.map {|i| i / 0}
.map {|i| i / 10}
#=>Error(divided by 0)
Dealing with nested results
x = Ok(100)
x.map {|i| Ok(i / 2)}
#=> Ok(Ok(50))
x.map {|i| Ok(i / 2)}.join
#=> Ok(50)
y = Ok(10)
y.flat_map {|i| Ok(i/ 2)}
#=> Ok(5)
Development
After checking out the repo, run bin/setup
to install dependencies. Then, run rake spec
to run the tests. You can also run bin/console
for an interactive prompt that will allow you to experiment.
To install this gem onto your local machine, run bundle exec rake install
. To release a new version, update the version number in version.rb
, and then run bundle exec rake release
, which will create a git tag for the version, push git commits and tags, and push the .gem
file to rubygems.org.
Contributing
Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/result. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the Contributor Covenant code of conduct.
License
The gem is available as open source under the terms of the MIT License.