0

I'd like to make sure that my array stays like this in the view:

["Tue", "Wed", "Thu", "Fri", "Sat", "Sun", "Mon", "Tue"]

Instead of being converted to this:

["Tue", "Wed", "Thu", "Fri", "Sat", "Sun", "Mon", "Tue"]

The code in my erb file is for a highcharts graph:

categories: <%= @days %>,

In Rails, I have used the raw method:

After following advice from Messy &quot returned from Rails 3 controller to view and Use ruby array for a javascript array in erb. Escaping quotes

However, loading all of ActionView to use one method seems to defeat the object of Sinatra.

Is there a better way?

Community
  • 1
  • 1
Richard Burton
  • 2,230
  • 6
  • 34
  • 49

1 Answers1

2

I'm not sure why you get some escaping on the array right now, but this is what I put in an ERB view:

<% array = ["Tue", "Wed", "Thu", "Fri", "Sat", "Sun", "Mon", "Tue"] %>

<p><%= array.inspect %></p>
<p><%= array.inspect.gsub(/"/, '\"') %></p>

and this was the output:

["Tue", "Wed", "Thu", "Fri", "Sat", "Sun", "Mon", "Tue"]

[\"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\", \"Sun\", \"Mon\", \"Tue\"]

But the real question is "How do I get data from Sinatra into a javascript function?"

class App < Sinatra::Base

  get "/array", :provides => :json do
    content_type :json
    ["Tue", "Wed", "Thu", "Fri", "Sat", "Sun", "Mon", "Tue"].to_json
  end

end

and then call it via some jQuery (or whichever library you would prefer) compiled from coffeescript, of course :)

$.getJSON "/array", (res) ->
  # do something with the result

Which means:

  • you don't need to worry about escaping
  • the jQuery takes care of parsing the JSON response so you've just to work with an object
  • it's easier to test
  • you've got an API set up with a web app calling against it (i.e. the Sinatra way not the Rails way)
  • and you'll be doing something more similar to other people which will make getting help easier.
ian
  • 12,003
  • 9
  • 51
  • 107