Created
January 15, 2012 20:40
-
-
Save m2ym/1617130 to your computer and use it in GitHub Desktop.
Yet another Object#try and Object#try_to
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 Try | |
| (instance_methods - [:object_id, :__send__, :to_s]).each {|m| undef_method m } | |
| def initialize(object) @object = object end | |
| def method_missing(method, *args, &block) | |
| return nil unless @object.respond_to? method | |
| @object.send(method, *args, &block) | |
| end | |
| end | |
| class TryTo | |
| (instance_methods - [:object_id, :__send__, :to_s]).each {|m| undef_method m } | |
| def initialize(object) @object = object end | |
| def otherwise(object) @object || object end | |
| def method_missing(method, *args, &block) | |
| return nil.try_to unless @object.respond_to? method | |
| @object.send(method, *args, &block).try_to | |
| end | |
| end | |
| class Object | |
| def try() Try.new(self) end | |
| def try_to() TryTo.new(self) end | |
| end | |
| p 1.try.foobar # => nil | |
| p (1.try.to_f) # => 1.0 | |
| p (1.try < 10) # => true | |
| p ('hello'.try_to.upcase.do_something.otherwise false) # => false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment