Best way to generate javascript code in ruby (RoR)
I have seen some rails plugins开发者_高级运维 which generate javascript code dynamically using ruby.
1.
%Q ( mixed block of javascript and ruby )
2.
<<-CODE
some mixed ruby and javascript code
CODE
Being a java developer I don't understand
what those strange looking syntax mean ?
Is one way better than the other ?
can anyone point me to proper documentation about such things ?
The first syntax is Ruby's string literal syntax. Specifically, the %Q (capital Q as opposed to lower-case) means that the string will be interpolated. eg:
%Q[Here's a string with #{a_variable} interpolated!]
Note that you can use any arbitrary characters as the open and close delimiters.
The second syntax is Ruby's heredoc syntax. The dash after the opening <<
indicates that Ruby will strip whitespace from the beginning of input lines contained in the heredoc block.
Ruby on Rails ships with the Prototype JavaScript framework built-in already. It also ships with JS generator helper methods which generate the Prototype code dynamically based on Ruby code.
You needn't use these if you don't want to. In fact, I rarely use them or Prototype at all, as jQuery is my JS framework of choice. So one way is not "better" than the other (except in the general sense that heredoc is better than the string literal syntax for certain cases).
In Ruby %Q
provides a double quote delimited string, so:
%Q(mixed block of javascript and ruby) #=> "mixed block of javascript and ruby"
<<-CODE
is what Ruby calls a Here Document, or simply heredoc. This is a mechanism for creating free format strings whilst preserving special characters such as new lines and tabs.
A heredoc is created by preceding the text with <<
followed by the delimiter string you wish to use to mark the end of the text.
text = <<-DOC
To be, or not to be: that is the question
William Shakespeare
DOC
When this string is printed it appears exactly as it was entered, together with all the new lines and tabs:
To be, or not to be: that is the question
William Shakespeare
%Q
is the equivalent to a""
string in Ruby. But if you use such %Q-syntax, you don't need to escape double quotes.- It's a HEREDOC declaration. You also don't need to escape quotes there.
- Strings in Ruby.
Here you can find the details. Ruby with javascript
精彩评论