-
-
Save hyoshida/4c3b1c30296a4ed7a218 to your computer and use it in GitHub Desktop.
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 | |
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