Created
November 24, 2012 00:01
-
-
Save Roman2K/4137772 to your computer and use it in GitHub Desktop.
This file contains 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
Misplaced "ensures" in sample code from: | |
http://railsware.com/blog/2012/11/20/yield-gotcha-in-ruby-blocks/ | |
Always be careful when adding "ensure" statements. Variables used within its | |
block may not have been assigned if an exception is raised within the "begin" | |
block. In fact, this mistake is often the result of not bothering with a "begin" | |
statement altogether |
This file contains 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 ensured_with_file(name, &block) | |
puts "Open file" | |
f = File.open(name, "r") | |
yield f | |
ensure | |
# | |
# /!\ f may be nil if File.open raises | |
# | |
puts "Close file" | |
f.close | |
end |
This file contains 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 ensured_with_file(name, &block) | |
puts "Open file" | |
f = File.open(name, "r") | |
begin | |
yield f | |
ensure | |
puts "Close file" | |
f.close | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment