S.Richmond
S.Richmond

Reputation: 11558

Trying to render JS in RAILS causes issues

I'm currently implementing Highcharts to create graphs in my RAILS application. I'm using the lazy high charts gem to make it a lot cleaner. This works fine. The graphs work great. Unfortunately a few things weren't supported in the gem such as adding custom js events like a click event. I have to add the additional option code in the view.

You can view the relevant code below. The commented out click event works fine. This click event will successfully raise a browser alert window. The large block of js text below that is the more advanced click event I'd like to implement. Unfortunately I get the error below. I'm guessing its because RAILS is trying to parse the js text? I can't work it out.

<%= high_chart("my_id", @h) do |c| %>
    <%= #"options.series[4].point.events.click = function() {alert ('Category: ');}" %>
    <%= render :js => %{ 
            options.series[4].point.events.click = 
                function() {
                        hs.htmlExpand(null, {
                            pageOrigin: {
                                x: this.pageX,
                                y: this.pageY
                            },
                            headingText: this.series.name,
                            maincontentText: Highcharts.dateFormat('%A, %b %e, %Y', this.x) + ':<br/> ' + this.y + ' visits',
                            width: 200
                        });
                    }
                } %>
<% end %>

The error:

/home/scott/flux/app/views/cognos_mn_tickets/pbadata.html.erb:22: syntax error, unexpected ',', expecting ')'
...ext: Highcharts.dateFormat('%A, %b %e, %Y', this.x) +':<br/>...
...                               ^
/home/scott/flux/app/views/cognos_mn_tickets/pbadata.html.erb:22: unknown type of %string
... Highcharts.dateFormat('%A, %b %e, %Y', this.x) +':<br/> '+t...
...

Upvotes: 0

Views: 224

Answers (1)

Jordan Running
Jordan Running

Reputation: 106147

The problem is that when you start a string with %{ then it will end on the very next }—which is in the middle of your JavaScript code. Try using Heredoc syntax instead:

<%= high_chart("my_id", @h) do |c| %>
  <%= <<-END
      options.series[4].point.events.click = function() {
        hs.htmlExpand( null, {
          pageOrigin      : { x: this.pageX, y: this.pageY },
          headingText     : this.series.name,
          maincontentText : Highcharts.dateFormat('%A, %b %e, %Y', this.x) +
                            ':<br/> ' + this.y + ' visits',
          width           : 200
        } );
      }
    END
  %>
<% end %>

Upvotes: 1

Related Questions