Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Ruby objects to Javascript objects for interpolation

What is a good way to convert some common Ruby objects (like strings, hashes, arrays) into corresponding Javascript objects? For example, jQuery css() accepts a hash as an argument. Suppose I have a Ruby hash like this:

h = {"background-color" => "yellow", "color" => "green"}

I want to embed this ruby object into a string so that it becomes a valid javascript (jQuery) command. My best attempt now is to convert it via json like this:

"$('#foo').css(JSON.parse('#{h.to_json}'));"

but it is not working well. I want a more direct and working way to do it. Is there a good way?

like image 429
sawa Avatar asked Dec 03 '25 10:12

sawa


1 Answers

No need to convert to a string and then JSON.parse:

"$('#foo').css(#{h.to_json});"

Or if you break it out...

var h = #{h.to_json};
"$('#foo').css(h);"

Which is rendered to the client as:

var h = {"background-color":"yellow","color":"green"};
$('#foo').css(h);
like image 151
Larsenal Avatar answered Dec 04 '25 23:12

Larsenal