Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing javascript function from ruby string in hash

I have ROR Helper that build some Javascript code. In the helper I have Hash of options and variables that define this javascript code. One of them is string that holds JS function, the problem is it rendered as a string and not as function when using to_json.

How can I make it work?

Example:

In my helper I have this code:

h = {url: '/some/url', async: false}
h[success] = "function(result) {alert(result);}"

"<script type='text/javascript'> jQuery.ajax(#{h.to_json}); </script>"html_safe

This code will generates:

<script type='text/javascript'>
  jQuery.ajax({
    url: '/some/url',
    async: false,
    success: "function(result) {alert(result);}"
  });
</script>

What I wont to to achieve is that code (without the ".." in success part):

<script type='text/javascript'>
  jQuery.ajax({
    url: '/some/url',
    async: false,
    success: function(result) {alert(result);}
  });
</script>
like image 805
Dror Avatar asked Jun 05 '26 13:06

Dror


1 Answers

You could create a string out of h hash instead of using to_json; for example:

def js_code
  h = {url: '"/some/url"', async: false}
  h[:success] = "function(result) { alert(result); }"
  s = h.map { |k, v| "#{k}: #{v}" }.join(",")

  "<script type='text/javascript'> jQuery.ajax({#{s}}); </script>".html_safe
end

Notice that additional double quotes (") were added to '"/some/url"' in order to keep them in the final string.

Output:

<script type='text/javascript'> jQuery.ajax({url: "/some/url",async: false, success: function(result) { alert(result); }}); </script>
like image 86
Gerry Avatar answered Jun 07 '26 08:06

Gerry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!