views:

72

answers:

4

Hi,

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

  1. what those strange looking syntax mean ?

  2. Is one way better than the other ?

  3. can anyone point me to proper documentation about such things ?

A: 

Hi,

Here you can find the details. Ruby with javascript

gsoni
Hi, I don't want to use any library specific things. The code I mentioned before uses jQuery for example not prototype and doesn't depend on any library.
rangalo
A: 
  1. %Q is the equivalent to a "" string in Ruby. But if you use such %Q-syntax, you don't need to escape double quotes.
  2. It's a HEREDOC declaration. You also don't need to escape quotes there.
  3. Strings in Ruby.
floatless
Is there any other method to generate javascript code. Do I have to escape some chars in javascript when I use either of the two methods ?
rangalo
No, you don't have to escape.
floatless
+2  A: 

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
John Topley
+3  A: 

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).

Josh Lindsey
Variable interpolation explains why I saw some ruby in the js block. Actually, What I want to do is write a Ruby function which spits out javascript code depending on params. –
rangalo