Just Maybe
An implementation of the "Maybe" pattern.
The philosophy behind this implementation of Maybe
is to wrap optional values at the point of first contact.
So for example, instead of allowing Person.find
to return nil
you return a Maybe
wrapping either a Person
or nil
. This forces consumers of Person.find
to access the underlying value with try
, thus explicitly acknowledging the returned values could be a Person
or Nothing
.
The implementation is extremely simple, does no monkey patching and does not rely on method missing.
It has a tiny API, providing three methods nothing?
, something?
and try
.
Installation
Add this line to your applications Gemfile:
gem 'just_maybe'
And then execute:
bundle
Or install it locally with:
gem install just_maybe
Then load it using:
require 'just_maybe'
Examples
require 'just_maybe'
# => true
# Calling Maybe(object) returns that object wrapped in an instance of Just
Maybe('anything')
# => <Just:0x000000020e04f0 @object="anything">
# Calling Maybe(nil) returns an instance of Nothing
Maybe(nil)
# => <Nothing:0x000000020b1718>
# Instances of Just and Nothing respond to the predicate methods nothing? and something?
Maybe(42).nothing? # => false
Maybe(42).something? # => true
Maybe(nil).nothing? # => true
Maybe(nil).something? # => false
# When try is called on instances of Just it passes the underlying object to the block
# and returns the result of the block.
Maybe(40).try{|m| m.succ.succ } # => 42
# When try is called on instances of Nothing it returns nil
Maybe(nil).try{|m| m.succ.succ } # => nil
# A common pattern would be to use try || default
Maybe(41).try{|m| m.succ } || 0 # 42
Maybe(nil).try{|m| m.succ } || 0 # 0
Notice
The public interface of this gem was radically changed with the jump to version 1.0. If you were using version 0.2
or earlier you should pin the version in your Gemfile at "~> 0.2"
Related
- Null Objects and Falsiness
- If you gaze into nil, nil gazes also into you
- The Maybe Monad In Ruby
- Mondadic
- Rumonade
- Wrapped
Contributing
- Fork it
- Create your feature branch (
git checkout -b my-new-feature
) - Commit your changes (
git commit -am 'Added some feature'
) - Push to the branch (
git push origin my-new-feature
) - Create new Pull Request