Skip to content

Instantly share code, notes, and snippets.

@rwz
Created November 6, 2015 19:06
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 rwz/362676b580e59cdd4cef to your computer and use it in GitHub Desktop.
Save rwz/362676b580e59cdd4cef to your computer and use it in GitHub Desktop.
How ensure/return breaks throw/catch
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