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:
link_to "Example 1", "http://www.example.com", needs_confirmation? ?
:confirm => "Are you sure?" : nil # syntax error; nil can't be a hash
element
or
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 => "our_link_#{user.id}" # Syntax error
{:id => "our_link_#{user.id}"} # valid, but returns a hash that
ends up being an element of the options hash
{:id => "our_link_#{user.id}"}.flatten_into_my_parent_hash #
What's in my brain
end
Is there some elegant way to do this? I can build the hash as a variable
before the method call, of course, and optionally add elements, but...
ick.
Let's stipulate that these are contrived examples, and assume that the
helpers wouldn't allow :confirm => nil or :id => nil, and that
unique_link_id might want to leave off the ID, and that I can't control
the helper I'm calling. I'm more interested in the Ruby hash syntax than
in solving a Rails problem.
Is this a possible thing?
···
--
Posted via http://www.ruby-forum.com/.