JustMaybe

An implementation of the "Maybe" pattern.

The philosophy of this particular implementation of the Maybe pattern is that you should use the Maybe function to wrap values before returning them from any method that could potentially return nil. This forces the consumer of the returned object to pro-actively acknowledge that it could be nil by forcing them to use the try method to access it.

This implementation also does no monkey patching and does not rely on method missing or any other Ruby magic for it's implementation.

It also has a tiny API. Maybe objects respond to 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(nothing)
# => <Nothing:0x000000020b1718>

# Instances of Just and Nothing respond to the replicate 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

Notice

The public interace 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"

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Added some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request