Justin Skord
2 min readApr 25, 2019

Yes, you can use a rails instance variable inside a script tag!

Sometimes the easiest solution is the right one, this is definitely at least sometimes, ill even go as far as to say most of the time, the case in coding. Recently I was attempting to take data from an api and integrating it into a graph on my webpage. First, I pulled the data from the data.gov wepsite, which, by the way, is a great place to find all sorts of interesting json data, using unirest inside my rails app, as shown below:

ecoli_level = Unirest.get(‘https://data.cityofchicago.org/api/views/t62e-8nvc/rows.json?accessType=DOWNLOAD').body

now I loop through the data I obtained in that api to pull out arrays of my x_axis and then y_axis as shown below:

ecoli_level["data"].each do |level|
date = level[9].to_time
date_utc = date.to_f * 1000
ecoli_concentration = level[10].to_i
@data << [date_utc, ecoli_concentration]
end
render 'cable.html.erb'
end

Now .. I have an instance variable that is an array of arrays of multiple sets of x, y coordinates for my data. Can I use that instance variable inside the <script> tags on my cable.html.erb page? Absolutely (see below), for the longest time I just assumed that nothing but javascript was allowed inside these <script> tags . . . live and learn.

<script>
document.addEventListener('DOMContentLoaded', function () {
var myChart = Highcharts.chart('container', {
chart: {
type: 'spline'
},
title: {
text: 'Predicted Ecoli Levels in Chicago Beach Water, 2016 Alerts'
},
subtitle: {
text: 'Irregular time data in Highcharts JS'
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats: { // don't display the dummy year
month: '%e. %b',
year: '%b'
},
title: {
text: 'Date'
}
},
yAxis: {
title: {
text: 'Ecoli Levels (ppm)'
},
min: 0
},
tooltip: {
headerFormat: '<b>{series.name}</b><br>',
pointFormat: '{point.x:%e. %b}: {point.y:.2f} m'
},
plotOptions: {
spline: {
marker: {
enabled: true
}
}
},
colors: ['#6CF', '#39F', '#06C', '#036', '#000'],
series: [{
name: "Ecoli Levels in Chicago Beaches, 2016",
data: <%= @data %>
}, ]
})
});
</script>

No responses yet