Created
November 6, 2015 19:06
-
-
Save rwz/362676b580e59cdd4cef to your computer and use it in GitHub Desktop.
How ensure/return breaks throw/catch
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
def run_with_elapsed_time | |
time_at_start = Time.now | |
exception = nil | |
result = yield | |
rescue => e | |
exception = e | |
ensure | |
return [ result, exception, Time.now - time_at_start ] | |
end | |
def wrap(&block) | |
result, exception, elapsed = run_with_elapsed_time(&block) | |
status = "run in #{elapsed} seconds" | |
if exception | |
puts "#{status} and raised #{exception}" | |
raise exception | |
else | |
puts "#{status} and returned #{result}" | |
result | |
end | |
end | |
it "throw/catch normally" do | |
value = catch(:value) do | |
throw :value, 123 | |
this_is_never_run | |
end | |
expect(value).to eq(123) | |
end | |
it "interrupts throw/catch" do | |
value = catch(:value) do | |
wrap do | |
throw :value, 123 | |
this_is_still_not_run | |
end | |
end | |
# this fails with value=nil :( | |
expect(value).to eq(123) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment