2011-12-12 42 views
40

我使用jQuery移动与Ruby on Rails的。如何在Ruby符号中使用破折号“ - ”?

我想创建这意味着有data-role="button"出现在生成的HTML按钮链接。

我已经试过:

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

但后来,我得到一个错误

undefined local variable or method `role' for #<#<Class:0x007fdc25668ee8>:0x007fdc25658610> 

有没有办法使用:xxx符号逃脱破折号或我应该只使用"xxx"符号?

(我同意这是一个化妆品的问题,但我想我的代码是一致的,不喜欢例外)

回答

73

使用单引号周围的符号名称,用冒号前缀:

:'data-role' => 'button' 

这里是符号的很好的参考:

http://www.troubleshooters.com/codecorn/ruby/symbols.htm#_What_do_symbols_look_like

+2

或双引号 - 或者正常工作。还要注意,[不能用这样的方式逃脱了1.9备选哈希语法符号(http://stackoverflow.com/questions/2134702/ruby-1-9-hash-with-a-dash-在一个关键) – arcresu

+0

谢谢大家,我投了最全面的答案,但所有的贡献是值得欢迎的! :) –

+2

作为一种习惯,我平时使用的时候会有串插,单为当字符串应该是一成不变的双引号。 –

3

把它包在单引号:

:'data-role' => "button" 
2
<%= link_to "Play", game_play_path, :"data-role" => "button" %> 
+1

或可选择地使用直串'“数据角色”'。不需要它是一个符号。 #codegolf –

12

如果发现语法<%= link_to "Play", game_play_path, :"data-role" => "button" %>丑陋的,因为它使用了旧的Hash语法,另一种方式来做到这一点的是涉及使用Ruby 1.9的语法哈希是做到以下几点:

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

散列重叠在html输出中生成数据和角色之间的连字符。

谨慎,因为这只是用数据属性的东西的工作,但在你的情况下,它是一个更令人高兴的眼睛替代。

另外,如果你有更多的数据属性的东西,你可以在嵌套哈希写他们还有:

<%= link_to "Play", game_play_path, data: {role: "button", other1: "value1", other2: "value2"} %>