Created
December 18, 2014 22:11
-
-
Save asterite/f7f5c2901dbe906fa643 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
macro mockable_method(type, method) | |
class {{type}} | |
def {{method.id}} | |
if _mock = @_mock_{{method.id}} | |
_mock.call | |
else | |
previous_def | |
end | |
end | |
def _mock_{{method.id}}(&@_mock_{{method.id}} : -> _) | |
end | |
end | |
end | |
class Object | |
macro method_missing(name, args, block) | |
{% if name.starts_with?("_mock_") %} | |
def {{name.id}}(&@_mock_{{name.id}} : -> _) | |
end | |
{% else %} | |
{% previous_def %} | |
{% end %} | |
end | |
end | |
macro mock(var, method) | |
x._mock_{{method.id}} do | |
{{yield}} | |
end | |
end | |
class Foo | |
def coco | |
1 | |
end | |
def coco2(x, y) | |
x + y | |
end | |
end | |
# mockable_method Foo, coco | |
# mockable_method Foo, coco2 { |x, y| } | |
x = Foo.new | |
puts x.coco | |
puts x.coco2(10, 20) | |
x = Foo.new | |
mock(x, coco) do | |
2 | |
end | |
mock(x, coco2) do |a, b| | |
a * b | |
end | |
# puts x.coco | |
# puts x.coco2(10, 20) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment