uses of Ruby’s Object#tap

Ruby 1.9′s Object#tap method has always seemed useful to me, but until now I hadn’t met the chance to use it. Every other time it seemed like abusing it in some way.

Now I came to an old code. Consider this:

cgi.text_field( "name" => "myfield",
                "value" => value,
                "size" => 20,
                "maxlength" => maxlength
              )

I needed to turn that maxlength into a conditional attribute (omiting it if it’s nil).
One way would have been extracting the attributes into a separate variable:

attrs = {
          "name" => "myfield",
          "value" => value,
          "size" => 20
        }
attrs['maxlength'] = maxlength if maxlength
cgi.text_field( attrs )

But this separates visually the cgi.text_field() call from it’s arguments, which I don’t like. Tap to the resque:

cgi.text_field({  "name" => "myfield",
                  "value" => value,
                  "size" => 20
                }.tap{|attrs| 
                  attrs['maxlength'] = maxlength if maxlength
                })

Now, isn’t that nice! (OK, maybe it isn’t, but at least it is encompassed in the method call and makes it easy to spot all attributes).

Be Sociable, Share!

No related posts.

Leave a Comment

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>