Created
February 18, 2016 14:58
-
-
Save bcardiff/75b38f9f8e29538199d3 to your computer and use it in GitHub Desktop.
mtry macro for crystal
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
# sample of a macro that flood the method calls with `#try` | |
# as a POC it does not support methods with arguments | |
macro mtry(expr) | |
{% if expr.is_a?(Call) %} | |
mtry({{expr.receiver}}).try(&.{{expr.name}}) | |
{% else %} | |
{{expr}} | |
{% end %} | |
end | |
class Foo | |
@x = 0 | |
getter x | |
def m | |
@x += 1 | |
rand > 0.3 ? self : nil | |
end | |
end | |
f = Foo.new | |
f.try(&.m.try(&.m.try(&.m.try(&.m.try(&.m.try(&.m)))))) | |
puts f.x | |
g = Foo.new | |
mtry g.m.m.m.m.m.m | |
puts g.x |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment