You can use blocks to define a chunk of code that must be run under some kind of transactional control.
For example, you’ll often open a file, do something with its contents, and then want to ensure that the file is closed when you finish.
A naive implementation (ignoring error handling) could look something like the following:
[~/ruby/PROGRAMMINGRUBYDAVETHOMAS]$ cat block_for_transaction.rb class File def self.my_open(*args) result = file = File.new(*args) if block_given? result = yield file file.close end return result end end File.my_open("testfile", "r") do |file| while line = file.gets print line end endThe responsibility for closing an open file has been shifted from the users of file objects back to the file objects themselves.
[~/ruby/PROGRAMMINGRUBYDAVETHOMAS]$ ruby block_for_transaction.rb 1 2 3 finIf we wanted to implement this method properly, we’d need to ensure that we closed a file even if the code processing that file somehow aborted.
my_openmethod to support some sort of rolling back transaction, making a backup copy of the file being open, and then restoring it if an exception is produced or deleting it if everything went fine.
Casiano Rodriguez León 2015-01-07