maybe
A library for treating nil and non-nil objects in a similar manner. Technically speaking, Maybe is an implemenation of the maybe monad.
Synopsis
The Maybe class wraps any value (nil or non-nil) and lets you treat it as non-nil.
"hello".upcase #=> "HELLO"
nil.upcase #=> NoMethodError: undefined method `upcase' for nil:NilClass
Maybe.new("hello").upcase.value #=> "HELLO"
Maybe.new(nil).upcase.value #=> nil
You can also use the method Maybe for convenience. The following are equivalent:
Maybe.new("hello").value #=> "hello"
Maybe("hello").value #=> "hello"
When you call Maybe.new with a value, that value is wrapped in a Maybe object. Whenever you call methods on that object, it does a simple check: if the wrapped value is nil, then it returns another Maybe object that wraps nil. If the wrapped object is not nil, it calls the method on that object, then wraps it back up in a Maybe object.
This is especially handy for long chains of method calls, any of which could return nil.
# foo, bar, and/or baz could return nil, but this will still work
Maybe.new(foo).(1).baz(:x)
Here’s a real world example. Instead of writing this:
if(customer && customer.order && customer.order.id==newest_customer_id)
# ... do something with customer
end
just write this:
if(Maybe.new(customer).order.id.value==newest_customer_id)
# ... do something with customer
end
Examples
Maybe.new("10") #=> A Maybe object, wrapping "10"
Maybe.new("10").to_i #=> A Maybe object, wrapping 10
Maybe.new("10").to_i.value #=> 10
Maybe.new(nil) #=> A Maybe object, wrapping nil
Maybe.new(nil).to_i #=> A Maybe object, still wrapping nil
Maybe.new(nil).to_i.value #=> nil
Related Reading
-
MenTaLguY has a great tutorial on Monads in Ruby over at Moonbase
-
Oliver Steele explores the problem in depth and looks at a number of different solutions
-
Weave Jester has another solution, inspired by the Maybe monad
Note on Patches/Pull Requests
-
Fork the project.
-
Make your feature addition or bug fix.
-
Add tests for it. This is important so I don’t break it in a future version unintentionally.
-
Commit, do not mess with rakefile, version, or history. (if you want to have your own version, that is fine but
bump version in a commit by itself I can ignore when I pull)
-
Send me a pull request. Bonus points for topic branches.
Copyright
Copyright © 2010 Ben Brinckerhoff. See LICENSE for details.