Created
February 9, 2011 17:38
-
-
Save rbxbx/818870 to your computer and use it in GitHub Desktop.
Object#maybe - A (crude?) implementation of the Maybe monad in Ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class BlankSlate | |
| instance_methods.each { |m| undef_method m unless m =~ /^__/ } | |
| end | |
| class MaybeProxy < BlankSlate | |
| attr_reader :obj | |
| def initialize(obj) | |
| @obj = obj | |
| end | |
| def method_missing(meth, *args, &blk) | |
| MaybeProxy.new(obj.try(meth, *args, &blk)) | |
| end | |
| end | |
| class Object | |
| def maybe(&blk) | |
| (yield MaybeProxy.new(self)).obj | |
| end | |
| def try(method, *args, &block) | |
| send(method, *args, &block) if respond_to?(method) | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment