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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With