How to escape a dash "-" in a Ruby symbol?
I'm using jquery-mobile with Ruby On Rails.
I want to create a button link which implies to have data-role="button"
appear in the generated HTML.
I've tried:
<%= link_to "Play", game_play_path, :data-role => "button" %>
But then, I get an error
undefined local variable or method `role' for #<#<Class:0x007fdc25668ee8>:0x007fdc25658610>
Is there a way to escape the dash using the :xxx
notation or should I just use the "xxx"
notation?
(I agree it's a cosmetic question, but I want my code to be consistent and don't like exceptions)
Use single quotes around the symbol name, with the colon prefix:
:'data-role' => 'button'
And here is a nice reference on symbols:
http://www.troubleshooters.com/codecorn/ruby/symbols.htm#_What_do_symbols_look_like
After Ruby 1.9
you can also do
'data-role': 'button'
If you find the syntax <%= link_to "Play", game_play_path, :"data-role" => "button" %>
ugly because it uses the old hash syntax, another way to do it that involves using ruby 1.9 syntax for hashes is to do the following:
<%= link_to "Play", game_play_path, data: {role: "button"} %>
The hash imbrication generates the hyphen between data and role in the html output.
Be cautious because this only works with data-something attributes, but in your case it's a more eye pleasing alternative.
Also, if you have more data-something attributes, you can write them as well in the nested hash:
<%= link_to "Play", game_play_path, data: {role: "button", other1: "value1", other2: "value2"} %>
Wrap it in single quotes:
:'data-role' => "button"
<%= link_to "Play", game_play_path, :"data-role" => "button" %>