56

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)

Mick F
  • 7,312
  • 6
  • 51
  • 98

4 Answers4

96

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'
Obromios
  • 15,408
  • 15
  • 72
  • 127
Andrew Kuklewicz
  • 10,621
  • 1
  • 34
  • 42
  • 2
    Or double quotes - either works fine. Also note that you [can't use a symbol escaped in such a way with the 1.9 alternative hash syntax](http://stackoverflow.com/questions/2134702/ruby-1-9-hash-with-a-dash-in-a-key) – Carl Suster Dec 13 '11 at 14:15
  • Thanks everyone, I voted for the most complete answers but all the contributions were welcome! :) – Mick F Dec 13 '11 at 15:10
  • 2
    As a habit, I usually use double quotes for when there will be string interpolation, and single for when the string ought to be immutable. – Andrew Kuklewicz Sep 28 '12 at 15:51
15

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"} %>
Daniel Ristic
  • 710
  • 6
  • 16
4

Wrap it in single quotes:

:'data-role' => "button"
mipadi
  • 398,885
  • 90
  • 523
  • 479
2
<%= link_to "Play", game_play_path, :"data-role" => "button" %>
clyfe
  • 23,695
  • 8
  • 85
  • 109