How to escape a dash "-" in a Ruby symbol?

RubyRuby on-Rails-3Jquery Mobile

Ruby Problem Overview


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)

Ruby Solutions


Solution 1 - Ruby

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'

Solution 2 - Ruby

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"} %>

Solution 3 - Ruby

Wrap it in single quotes:

:'data-role' => "button"

Solution 4 - Ruby

<%= link_to "Play", game_play_path, :"data-role" => "button" %>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDirty HenryView Question on Stackoverflow
Solution 1 - RubyAndrew KuklewiczView Answer on Stackoverflow
Solution 2 - RubyDaniel RisticView Answer on Stackoverflow
Solution 3 - RubymipadiView Answer on Stackoverflow
Solution 4 - RubyclyfeView Answer on Stackoverflow