How to pass options directly to the charting library in Chartkick

Chartick is a great gem which gluing popular JavaScript charting libraries (Chart.js, Google Charts and Highcharts) with Ruby (and other languages) templates. But, because Chartick is abstraction with its options, it is not really clear how to configure the underlying JavaScript library which for the first time cost me some extra time of debugging and digging its source code.

Of course, after I found the solution, I also found the documentation on this functionality 🙂 (one of the last lines in Charick Options section).

To simplify finding of this functionality by myself and maybe other in future I decided to write this blog post.

Applying options directly to the JavaScipt charting library

All examples applying to Chart.js library.

Locally for one chart

<%= line_chart data,
               library: {tooltips: {backgroundColor: 'rgba(100,0,0,0.8)'}} %>

Globally for all charts

with config initializer

Add to initializer config/initializers/chartkick.rb:

Chartkick.options = {
  library: {animation: {easing: 'easeOutQuart'}},
}

with Webpacker

Add to pack file:

import Chartkick from 'chartkick'
import Chart from 'chart.js'

window.Chartkick = Chartkick
Chartkick.addAdapter(Chart)
Chartkick.options = {
  library: {animation: {easing: 'easeOutQuart'}},
}

There are many complaints about animating with Turbolinks. Mainly they all come from Turbolinks Caching mechanism. And actually it is not the issue, it is how Turbolinks Caching works.

Simplest solution to overcome this "issue" is to disable caching on page with animation by adding <meta name="turbolinks-cache-control" content="no-cache"> element in your page's <head>.

More complex and context-dependent solution is to handle Turbolinks Events with necessary logic.

For example one possible solution for Chartick is to handle turbolinks:render and disable library animation if render page from cache:

document.addEventListener('turbolinks:render', function () {
  if (document.documentElement.hasAttribute('data-turbolinks-preview')) {
    Chartkick.eachChart(function (chart) {
      chart.updateData(null)
      chart.setOptions({...chart.getOptions(), ...{library: {animation: false}}})
    })
  }
})