Languages

Fsharp
ActionScript
xBase
Clean
GPSS
PureBasic
Sieve
Erlang
JOVIAL
Mercury
Linda
DataFlex
PostScript
FoxPro2
VFP
Cobol
Prolog
Jython
Awk
VisualBasic
JavaScript
Matlab
ASP
Haskell
Csharp
D
Smalltalk
Nemerle
Pixilang
Java
SQL
Python
ObjectPascal
Ruby
Perl
Pascal
Assembler
PHP
C
Functions  Add function  Users  Registration  Enter   About  ASCII Table  Our helpers

Ruby-on-Rails


1 Exploring Iteration

2 7.9 Looping Through Multiple Iterables in Parallel

3 7.10 Hiding Setup and Cleanup in a Block Method

4 7.11 Coupling Systems Loosely with Callbacks

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

  1. 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
  2. Recipe 11.9, “Creating and Modifying XML Documents”
  3. 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
1 2 3 4
Genetic Structure of First Animal to Show Evolutionary Response to Climate Change Determined

Photo of a water-filled purple pitcher plant leaf.

Scientists at the University of Oregon have determined the fine-scale genetic structure of the first animal to show an evolutionary response to rapid climate change.

They used a high-throughput sequencing technique called Restriction-site Associated DNA (RAD) tagging to make the discovery.

Their results, which focus on the pitcher plant mosquito, Wyeomyia smithii, are published this week in the journal Proceedings of the National Academy of Sciences (PNAS). ...

More at http://www.nsf.gov/news/news_summ.jsp?cntn_id=117577&WT.mc_id=USNSF_51&WT.mc_ev=click


This is an NSF News item.

PycckaR
BepcuR


Articles
Articles


Library
Library


Downloads
Downloads

Google Chrome Golf 6
 © Internet, books, teachers and Rudevich Alexander brains.