Skip to content

Instantly share code, notes, and snippets.

@hyoshida
Forked from kkismd/maybe.rb
Last active August 29, 2015 14:04
Show Gist options
  • Save hyoshida/4c3b1c30296a4ed7a218 to your computer and use it in GitHub Desktop.
Save hyoshida/4c3b1c30296a4ed7a218 to your computer and use it in GitHub Desktop.
class Maybe < BasicObject
UNPROXIED_METHODS = %i(__send__ __id__ send object_id extend instance_eval initialize block_given? raise caller method)
delegate *(::NilClass.instance_methods - UNPROXIED_METHODS), to: :@just
def initialize(obj)
@just = obj
end
# for debug
def inspect
"#<Maybe: just(#{@just.inspect})>"
end
def just!
@just
end
def method_missing(method, *args, &block)
if @just.respond_to?(method)
val = @just.__send__(method, *args, &block)
else
val = nil
end
::Maybe.new(val)
end
end
=begin
How To Use
before:
<%= @user.try(:section).try(:company).try(:name) %>
after:
<%= maybe(@user).section.company.name %>
where:
ApplicationHelper
def maybe(obj)
Maybe.new(obj)
end
end
=end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment