Skip to content

Instantly share code, notes, and snippets.

@m2ym
Created January 15, 2012 20:40
Show Gist options
  • Select an option

  • Save m2ym/1617130 to your computer and use it in GitHub Desktop.

Select an option

Save m2ym/1617130 to your computer and use it in GitHub Desktop.
Yet another Object#try and Object#try_to
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