Utilizing google chart for plotting a graph in my Rails application.
The data used for the chart is dynamically generated within a model.
Company#my_chart_data
def my_chart_data
[
['date', 'value1', 'value2'],
[Date.new(2017,1,11), 1, 2],
[Date.new(2017,1,13), 3, 5],
[Date.new(2017,1,16), 0, 7]
]
end
In the view, the method is invoked to fetch the chart data.
<%= content_tag :div, "", id: "my-chart-data",
data: {rows: company.my_chart_data} %>
Subsequently, the chart is generated using JavaScript.
An important step involves converting date strings into Date
objects due to Ruby's conversion of Date
instances into strings.
function drawMarginBalance(type) {
var array = $('#my-chart-data').data('rows');
// convert date string to date object
array = array.map(function (obj) {
if (obj[0].match(/\d{4}-\d{2}-\d{2}/)) {
return [new Date(obj[0])].concat(obj.slice(1, 3));
} else {
return obj;
}
});
var data = google.visualization.arrayToDataTable(array);
var options = {
seriesType: 'bars',
series: {1: {type: 'line'}}
};
new google.visualization.ComboChart(document.getElementById('my-chart')).draw(data, options);
}
The code performs as expected. However, I aim to input a Date
object instead of a String
within the data-
attributes.
Seeking guidance on how to accomplish this task efficiently.