Ruby’s beauty is often attrib­uted to its terse­ness. How­ever, there are times when you need to be really explicit in order to coax it to do your bid­ding. For exam­ple, a Rails form helper needs a bunch of paran­the­ses and curly braces in order to be a named ele­ment. Which makes sense, as :id can rep­re­sent a Rails (ActiveRe­cord) object ID or a DOM ele­ment ID. The Ruby punc­tu­a­tion removes such ambiguity.

<%= form_tag( {:controller => 'controller', :action => 'action', :id => 1}, {:id => 'test', :name => 'test'} )%>

This code then pro­duces this HTML.

<form action="/controller/action/1" id="test" method="post" name="test">

Not using the punc­tu­a­tion results in the ID being gob­bled up by the URL, or attrib­utes being tacked on to the URL as query string val­ues, or an oh so help­ful com­pile error. Mmmm taste the sarcasm.

The only ref­er­ence to this was found, not in the API, but buried in some Rails mail­ing list thread indexed by Google. I fig­ured I’d pre­serve this tid­bit for pros­per­ity see­ing how I couldn’t find it on another blog.

Note: Nam­ing form_remote_tag is done dif­fer­ently. After deci­pher­ing the syn­tax by look­ing at the source code for the helper, it turns out the key is the :html option.

<%= form_remote_tag :url => {:controller => 'controller', :action => 'action', :id => 1}, :html => {:id => 'test', :name => 'test'} %>

Comments are closed.