Note that there are some explanatory texts on larger screens.

plurals
  1. POAdd a non-literal hash element to Ruby's last-argument magic hashes?
    primarykey
    data
    text
    <p>Many Rails helpers use an idiomatic options hash as their last argument; Ruby automatically inserts extra method arguments into that hash. I often find myself wanting to conditionally insert an element, or to write a helper that provides the element. Two examples in pseudo-Ruby:</p> <pre><code>link_to "Example 1", "http://www.example.com", needs_confirmation? ? :confirm =&gt; "Are you sure?" : nil # syntax error; nil can't be a hash element </code></pre> <p>or</p> <pre><code>link_to "Example 2", "http://www.example.com", unique_link_id # I don't want to return a hash; I want to return an element of a hash def unique_link_id :id =&gt; "our_link_#{user.id}" # Syntax error {:id =&gt; "our_link_#{user.id}"} # valid, but returns a hash that ends up being an element of the options hash {:id =&gt; "our_link_#{user.id}"}.flatten_into_my_parent_hash # What's in my brain end </code></pre> <p>Is there some elegant way to do this? I can't control the Rails helpers, obviously, so I can't force them to flatten the hash. (Er, not that there's a <code>Hash#flatten</code> method, but even if there were.)</p> <p>I can build the hash as a variable before the method call, of course, and optionally add elements, but... ick.</p> <p>Let's stipulate that these are contrived examples, and assume that the helpers wouldn't allow <code>:confirm =&gt; nil</code> or <code>:id =&gt; nil</code>, and that <code>unique_link_id</code> might want to leave off the ID. I'm more interested in the hash syntax than in solving a Rails problem.</p> <p>Anyone? </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload