Created
July 31, 2014 09:06
-
-
Save kkismd/a405aa0a4e27588598ff to your computer and use it in GitHub Desktop.
Uncertain method chain without #try
This file contains 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 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