Mona::Result
Provides a result monad, with OK holding a value, and Err holding a failure, with optional reason, and metadata.
Also provides a dict result monad, a hash-like result, which provides #sequence
whose semantics mirror do notation
Installation
Install the gem and add to the application's Gemfile by executing:
$ bundle add mona-result
If bundler is not being used to manage dependencies, install the gem by executing:
$ gem install mona-result
Usage
Result = Mona::Result
success = Result.ok(1)
success.ok?
success.err?
success.value
success.and_tap { puts "it is #{_1}" }
.and_then { _1 * 5 }
.value_or { :nope }
failure = Result.err(4, :not_prime)
failure.ok?
failure.err?
failure.failure
failure.reason
failure.and_tap { puts "it is #{_1}" }
.and_then { _1 * 5 }
.value_or { :nope }
result = Result.dict do |d|
d.set :user, UserRepo.find user_id
d.set :input, PostInput.valid(attributes)
d.set [:post, :input], PostRepo.create user_id: user_id, **d[:input]
end
divide = Result.action do |x, y|
set :numerator, x
set :divisor, y.zero? ? Result.err(y, :is_zero) : y
puts "ready to calculate answer"
set :answer, numerator / divisor
puts "answer was: #{answer}"
end
divide.call(12, 4)
result = divide.call(12, 0)
result.err?
result.failure
result.reason
result.meta
Pattern matching is supported in the following way:
case result
in :ok, value
in :err, failure, reason, { **meta }
end
case result
in ok:
in err:, reason:, **meta
end
You can also match a result, using similar semantics, the difference from using case/pattern-match is that a
Mona::Result::NoMatchError
is raised, which keeps a reference to the result (which is useful for differentially
handling errors in an enclosing scope - not currently possible with ruby's NoMatchingPatternError
which does not
contain any information about the failed match)
Mona::Result.match(result) do |on|
on.ok { |value| puts "ok" }
on.err(key: :x) { |failure, reason, **meta| puts "error with meta :key => :x" }
on.err(:invalid) { |failure, reason, **meta| puts "error with reason :invalid" }
on.err { |failure, reason, **meta| puts "error" }
end
Development
After checking out the repo, run bin/setup
to install dependencies. Then, run rake test
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 the created tag, and push the .gem
file to rubygems.org.
Contributing
Bug reports and pull requests are welcome on GitHub at https://github.com/mona-rb/mona-result.
License
The gem is available as open source under the terms of the MIT License.