Skip to content

Instantly share code, notes, and snippets.

@Sija
Last active July 25, 2016 02:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Sija/62a90dcaabb7f9cbaa804493fb15631e to your computer and use it in GitHub Desktop.
Save Sija/62a90dcaabb7f9cbaa804493fb15631e to your computer and use it in GitHub Desktop.
class AssertionError < Exception
end
# If `cond` is `false`, raise `exc`.
# If `exc` is not provided, `AssertionError` will be raised instead with information about the faulty expression.
# If the expression is a comparison, the result of each side of the comparison will also be shown.
macro assert(cond, exc = nil)
unless {{ cond }}
{% if exc %}
raise {{ exc }}
{% else %}
{% if cond.is_a? Call && %w(== != < > <= >=).any? {|s| s == cond.name.stringify} %}
{% a = cond.receiver; b = cond.args[0] %}
%error = "#{{{ a.stringify }}} => #{{{ a }}} {{ cond.name }} #{{{ b }}} <= #{{{ b.stringify }}}"
{% else %}
%error = {{ cond.stringify }}
{% end %}
raise AssertionError.new(%error)
{% end %}
end
end
# Assert only in debug mode
macro debug_assert(cond, exc = nil)
ifdef !release
assert({{ cond }}, {{ exc }})
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment