Ruby Array to Java Script Array

Hi,

How can we use an array created in Ruby in Java script ?

Regards, Prashant

Hi,

How can we use an array created in Ruby in Java script ?

Convert it to appropriate strings and include it in the script. Remember that the view template is run in the server generating text that is passed to the browser. Then the javascript is run in the browser.

Colin

Colin Law wrote:

Hi,

How can we use an array created in Ruby in Java script ?

Convert it to appropriate strings and include it in the script.

You can retrieve the appropriate string by simply saying:

  array.to_json

Consider using something like

  <%= javascript_tag( yield :js_declarations ) %>

in your application.html.erb and

  <% content_for :js_declarations, "var array = #{@array.to_json};" %>

in the view.

Regards, T.

Use array.to_json and send it over to the client. For example, you could use an AJAX call to do that.

- Aleksey

I tried using json but I am doing some mistake because of which I am not able to get value properly I have such code in ruby file     @files = Dir.glob("*.txt").to_json In view file   var files= ('<%= h @files -%>'); When I see the alert I get a complete string containing list of all files When I run this alert I see one character printed at a time iso a single file name.   for(i=0;i<3;i++)     {       alert(files[i]);     }

I am making some mistake in using json but could not figure out what. Can you please help ?

Have a look at the html source of the page (View/Page Source or similar in browser) and see what you generating. Then you should be able to work out what is wrong.

Colin

Colin Law wrote:

           alert\(files\[i\]\);
     \}

I am making some mistake in using json but could not figure out what.

Have a look at the html source of the page (View/Page Source or similar in browser) and see what you generating. Then you should be able to work out what is wrong.

For this you should of course know that JS doesn't only not need HTML-escaping but doesn't understand it. So

  var files = [&quot;bla&quot;,&quot;blubb&quot;];

is syntactically wrong. Should be:

  var files = ["bla","blubb"];

This means: never use h (<%h %>) for Javascript.

T.

T. N. T. wrote:

Colin Law wrote:

Hi,

How can we use an array created in Ruby in Java script ?

Convert it to appropriate strings and include it in the script.

You can retrieve the appropriate string by simply saying:

  array.to_json

Consider using something like

  <%= javascript_tag( yield :js_declarations ) %>

in your application.html.erb and

  <% content_for :js_declarations, "var array = #{@array.to_json};" %>

in the view.

That's kind of a bad way of doing it. Instead, put the JSON in a hidden div in your HTML, then have your JS read it from there. This will avoid mixing JS and HTML.

Regards, T.

Best,