Using Javascript in Ruby with Materialize + Google Charts

As it so happens, erb(Ruby) can be seamlessly used within inline Javascripts. I started working with Google Charts for the Kpi tracking app I’m building and was looking for a fast way to integrate it into my view when I ran into an issue where I needed to translate a SQL stored date into a Javascript date to be readable by my chart data type. Instead of translating my date via ISO I pulled out the individual values to create a new JS one. My worry was that I wanted to be able to easily comprehend my code when looking at a later date and to not break it if I choose to change my SQL data date type. My implementation below is a longer, but more flexible approach.

<script type="text/javascript">
	google.charts.load('current', {packages: ['corechart', 'line']});
	google.charts.setOnLoadCallback(drawBackgroundColor);

	function drawBackgroundColor() {
	      var data = new google.visualization.DataTable();
	      data.addColumn('date', 'Updated');
	      data.addColumn('number', 'Amount');

	      var mets = []
	      
	      <%kpi.metrics.each do |i|%>
		  var v = [new Date(<%=i.created_at.year%>, <%=i.created_at.month%>, <%=i.created_at.day%>)]
		  v.push(<%=i.metric%>)
	          mets.push(v)
	      <%end%>
	      data.addRows(mets)

	      var options = {
	        hAxis: {	    				          
	          gridlines: {
	          	color: 'transparent'
	          },
	          baselineColor: '#000000',
	          textStyle: {
	          	color: 'black'
	          }
	        },
	        vAxis: {	    				          
	          gridlines: {
	          	color: 'transparent'
	          },
	          baselineColor: '#000000',
	          textStyle: {
	          	color: 'black'
	          }
	        },
	        series: {
                0: { color: '#000000', lineWidth: 1 },
                1: { color: '#000000', lineWidth: 1 }
            },
	        legend: 'none',
	        backgroundColor: '#ffffff'
	      };

	      var chart<%=kpi.id%> = new google.visualization.LineChart(document.getElementById('chart_div-<%=kpi.id%>'));
	      chart<%=kpi.id%>.draw(data, options);
	    }
</script>

ActiveRecord Finder & Query Methods

In my domain I have a company that has_many kpis with a goal value associated to it. Each company kpi has_many metrics or “metric updates”. The idea behind this is that a company is able to update each of the kpis’ progress towards their goal by adding new metric updates. However, I felt it was important to save all of these metrics so that the team could see progress charted over time. Thus, a “metric update” is really creating a new metric that belongs_to the company’s kpi. In coding this portion of my app I found a couple of Rails specific methods infinitely helpful in keeping my code clean.

I’ve come to despise code that uses uses conditional statements like this using nil because, well, it doesn’t sound like plain English and it’s ugly. I find SQL sort statements to be entirely unpleasant and have fallen for ActiveRecord’s auto-magic methods Exists? ActiveRecord Finder method and ActiveRecord Ordering Query Methods.

if something == nil
  return somethingelse
end
SELECT "metrics".* FROM "metrics" WHERE "metrics"."kpi_id" = ? ORDER BY "metrics"."created_at" DESC

I mean just look how beautiful and effortless these methods make my particular example. <3

<%@company.kpis.each do |kpi|%>
  <%if kpi.metrics.exists?%>	 
    <ul class="collection">
      <%kpi.metrics.order(created_at: :desc).each do |mt|%>
        <li class="collection-item">
          Last Updated to <%=mt.metric%> on <%=mt.created_at.to_formatted_s(:long)%>
          <%=link_to "Delete", company_kpi_metric_path(@company, kpi, mt), method: :delete %>
        </li>
      <%end%>
    </ul>
  <%end%>
<%end%>