Skip to content

Instantly share code, notes, and snippets.

@kkismd
Created July 31, 2014 09:06
Show Gist options
  • Save kkismd/a405aa0a4e27588598ff to your computer and use it in GitHub Desktop.
Save kkismd/a405aa0a4e27588598ff to your computer and use it in GitHub Desktop.
Uncertain method chain without #try
class Maybe < BasicObject
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
# don't mimic converting or query method
if method.to_s.start_with?('to_') || val == true || val == false
val
else
::Maybe.new(val)
end
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