Skip to content

Instantly share code, notes, and snippets.

@bcardiff
Created February 18, 2016 14:58
Show Gist options
  • Save bcardiff/75b38f9f8e29538199d3 to your computer and use it in GitHub Desktop.
Save bcardiff/75b38f9f8e29538199d3 to your computer and use it in GitHub Desktop.
mtry macro for crystal
# 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