Create a beautiful chart with just one line. For those who loves Ruby but does not like JavaScript

Create a beautiful chart with just one line. For those who loves Ruby but does not like JavaScriptMay 4, 2018

It is nice to have charts in the Ruby on Rails app but it’s sometimes difficult to prepare proper data and then display it using JavaScript in the view. Let me introduce you the solution: Chartkick and Chartable gems.

Chartkick is a gem for displaying beautiful and useful charts just with one line of code. Chartable is a gem for transforming any Active Record query to the analytics hash. Using both gems gives you a new superpower – chart creation.

The configuration

Let’s start with adding new gems to our Gemfile:

gem 'chartkick'
gem 'chartable'

After running bundle install we have to load JavaScript library for rendering charts. In order to do this, update the application.js file and add these lines:

//= require Chart.bundle
//= require chartkick

Getting the analytics data

Let’s assume that you have a blog engine created with Ruby on Rails and there is a Article model. We want to show how many articles were created in a given month. In order to do this we have to perform one query:

@articles = Article.analytics(:monthly)

If you created one article in April and five in May then you should have such hash:

{"April 2018" => 1, "May 2018" => 5}

Displaying the chart

Now it’s time to show our data in the view. As I said, you need only one line:

Download free RSpec & TDD ebook

Do you want to earn more or jump to the next level in your company? Do you know that testing skills are one of the most desired skills? There is only first step: start testing and do it right. My ebook can help you.
Subscribe to the newsletter to get a free copy of the book.