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

Ruby on Rails / Development

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:

<%= pie_chart(@articles) %>

and we are done! If you want to use a different chart or fetch data for different periods please check gems pages on the Github: https://github.com/ankane/chartkick and https://github.com/rubyhero/chartable