Subsecciones

Bloques para las Transacciones

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
end
The 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
fin
If 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.

  1. As a similar example, we could extend this my_open method 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.

Véase

  1. Ruby Best Practices. Code Blocks: Ruby's Swiss Army Knife. 2009-07-07 written by Gregory Brown

Casiano Rodriguez León 2015-01-07