[RUBY] Draw a graph with Sinatra and Chartkick

Introduction

I improved the * family todo list* created last time and tried to draw a graph.

Completion screen

20200828.png

Setting

main.rb


require 'sinatra'
require 'sinatra/reloader'
require 'date'
require 'active_record'
require 'rack/csrf'
require 'chartkick'  #add to

bash.sh


$ ls public/
chartkick.js  main.js  style.css

Put chartkick.js in public

Source

main.rb


get '/' do
  con = ActiveRecord::Base.connection
  dat = con.execute("select users.name, scores.score, scores.point from users inner join scores on users.id = scores.user_id where scores.flag=0 order by users.name, scores.point")
  h = {name: '', data: {}}
  @graph_data = []
  tname = ''
  dat.each do |x|
    if x["name"] == tname
      h[:data][x["point"]] = x["score"]
    else
      tname = x["name"]
      if h[:name] != ''
        @graph_data << h.dup
      end
      h[:name] = x["name"]
      h[:data] = {}
      h[:data][x["point"]] = x["score"]
    end
  end
  @graph_data << h.dup
  erb :index
end

Originally, you should use ʻActiveRecord well, but you can get the data by typing SQL` directly.

index.erb


<%= line_chart @graph_data, min: 40, max: 100 %>

It is thanks to gem that it is drawn beautifully.

Summary

Referenced site Create beautiful JavaScript charts with one line of Ruby

Recommended Posts

Draw a graph with Sinatra and Chartkick
Draw a bar graph and a line graph at the same time with MPAndroidChart
Draw a gradient with CAGradientLayer
Draw a pie chart with Chart.js
Make a family todo list with Sinatra
Make a family todo list with Sinatra
Prepare a scraping environment with Docker and Java
Try drawing a cube with View and Layer
A simple rock-paper-scissors game with JavaFX and SceneBuilder
Design and implement a breakout game with a clean architecture
Let's make a LINE Bot with Ruby + Sinatra --Part 2
Design and implement a breakout game with a clean architecture
[Ruby] I made a crawler with anemone and nokogiri.
Let's make a LINE Bot with Ruby + Sinatra --Part 1
[Swift 5] Draw a line.
Graph creation with JFreeChart
Create a blog with Jekyll and GitHub Pages @ Theme setting
Have fun programming with lambda expressions and a fluid interface
I want to make a list with kotlin and java!
I want to make a function with kotlin and java!
Create a blog with Jekyll and GitHub Pages @ Initial Settings
Build a Node-RED environment with Docker to move and understand
Socket communication with a web browser using Java and JavaScript ②
Install Ruby 3.0.0 Preview 1 with a combination of Homebrew and rbenv
Socket communication with a web browser using Java and JavaScript ①
Graph the sensor information of Raspberry Pi in Java and check it with a web browser