views:

78

answers:

1

Hi,

Here's what I want, in wishful code:

in my controller action:

@javascript_function_args = [ "foo", "bar", 1, [2, 3], { :zort => 'narf', :nom => 'cake' }]

in my erb view:

<script … >
  performAwesome(<%= @javascript_function_args.to_js_args %>);
</script>

or, even better:

  <%= call_javascript_function :performAwesome, *@javascript_function_args %>

my expected output:

<script … >
  performAwesome("foo", "bar", 1, [2, 3], { zort : 'narf', nom : 'cake' });
</script>

I suppose I could just #to_json the array and strip the wrapping brackets, but I'm wondering if there's something more specific to handle it.

A: 

Here's another way to do it that doesn't involve string manipulation.

In an appropriate helper (or you could monkey-patch Array if you prefer):

def to_js_args(array)
  array.map {|arg| arg.to_json}.join(",")
end
Greg Campbell