Created
August 7, 2014 01:24
-
-
Save whiteleaf7/08d0d3df2142c78123fc to your computer and use it in GitHub Desktop.
RubyでSwiftのOptionalChainingモドキ
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 NilClass | |
def method_missing(args) | |
nil | |
end | |
end | |
module Optional | |
def method_missing(method_name, *args) | |
if method_name =~ /\?$/ | |
search_name = method_name[0...-1] | |
if respond_to?(search_name) | |
__send__(search_name, *args) | |
else | |
nil | |
end | |
else | |
super | |
end | |
end | |
end | |
class Bar | |
def bar | |
puts "bar" | |
end | |
end | |
class Foo | |
include Optional | |
def foo | |
puts "foo" | |
Bar.new | |
end | |
end | |
Foo.new.foo?.bar | |
p Foo.new.bar?.foo | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment