7.10 Hiding Setup and Cleanup in a Block Method
(Page 3 of 4 )
Problem You have a setup method that always needs to run before custom code, or a cleanup method that needs to run afterwards. You don’t trust the person writing the code (possibly yourself) to remember to call the setup and cleanup methods. Solution Create a method that runs the setup code, yields to a code block (which contains the custom code), then runs the cleanup code. To make sure the cleanup code always runs, even if the custom code throws an exception, use a begin/finally block. def between_setup_and_cleanup setup begin yield finally cleanup end end Here’s a concrete example. It adds a DOCTYPE and an HTML tag to the beginning of an HTML document. At the end, it closes the HTML tag it opened earlier. This saves you a little bit of work when you’re generating HTML files. def write_html(out, doctype=nil) doctype ||= %{<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">} out.puts doctype out.puts _<html>_ begin yield out ensure out.puts _</html>_ end end write_html($stdout) do |out| out.puts _<h1>Sorry, the Web is closed.</h1>_ end # <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" # "http://www.w3.org/TR/html4/loose.dtd"> # <html> # <h1>Sorry, the Web is closed.</h1> # </html> Discussion This useful technique shows up most often when there are scarce resources (such as file handles or database connections) that must be closed when you’re done with them, lest they all get used up. A language that makes the programmer remember these resources tends to leak those resources, because programmers are lazy. Ruby makes it easy to be lazy and still do the right thing. You’ve probably used this technique already, with the theKernel#openandFile#openmethods for opening files on disk. These methods accept a code block that manipulates an already open file. They open the file, call your code block, and close the file once you’re done: open(_output.txt_, _w_) do |out| out.puts _Sorry, the filesystem is also closed._ end Ruby’s standardcgimodule takes thewrite_htmlexample to its logical conclusion.* You can construct an entire HTML document by nesting blocks inside each other. Here’s a small Ruby CGI that outputs much the same document as thewrite_htmlexample above. #!/usr/bin/ruby # closed_cgi.rb require _cgi_ c = CGI.new("html4") c.out do c.html do c.h1 { _Sorry, the Web is closed._ } end end Note the multiple levels of blocks: the block passed intoCGI#outsimply callsCGI#htmlto generate the DOCTYPE and the<html>tags. The<html>tags contain the result of a call toCGI#h1, which encloses some plain text in<h1>tags. The program produces this output: Content-Type: text/html Content-Length: 137 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <HTML><h1>Sorry, the Web is closed. </H1></HTML> TheXmlMarkup class in Ruby’sbuildergem works the same way: you can write Ruby code that resembles the structure of the document it creates: require _rubygems_ require _builder_ xml = Builder::XmlMarkup.new.message(_type_ => _apology_) do |b| b.content(_Sorry, Web Services are closed._) end puts xml # <message type="apology"> # <content>Sorry, Web Services are closed.</content> # </message> See Also - Recipe 6.13, “Locking a File,” uses this technique to create a method that locks a file, and automatically unlocks it when you’re done using it
- Recipe 11.9, “Creating and Modifying XML Documents”
- Recipe 20.11, “Avoiding Deadlock,” uses this technique to have your thread lock multiple resources in the right order, and unlock them when you’re done using them
|