Quck code examples: pie chart using Chart.js and a ruby hash

Here’s a quick code example of a pie chart using Chart.js and ruby/rails to get the top five schools entered by students and to display the number of times they appear. Read through the code comments for more information.

/dashboard_controller.rb

#pull the list of interns related to this application
@startup_application = current_startup.startup_applications.all.order('created_at DESC')

#pull the interns education from the column
internschools = Intern.where("education != ?", "NULL").pluck("education")

#count the number of similar schools
counts = Hash.new 0
internschools.each do |word|
counts[word] += 1
end

#sort all of the school counts highest to lowest and then get the top 5
@internschoolsfinal = Hash[counts.sort_by{|k, v| v}.reverse[0..4]]

/dashboard.html.erb


#give schoolnumber a start value
<% schoolnumber = 0 %>

#go through the hash received from the controller
<% @internschoolsfinal.each do |x| %>

#increment the school number by 1
<% schoolnumber += 1 %>

#set the schoolname variable based on the hash pair key value for input into the javascript file
var <%= "school#{schoolnumber}name" %> = "<%= x.first %>";

#set the schoolnumber variable similar to schoolname
var <%= "school#{schoolnumber}number" %> = <%= x.second %>;
<% end %>

#if the schoolnumber count didn't reach 5, make sure it reaches 5 so we don't throw a javascript exception for chart.js
<% if schoolnumber < 5 %>

#just make 5 empty school values
<% 5.times do |y| %>
<% schoolnumber += 1 %>

#call the school N/A and give it a count of 0, it won't show up on the chart anyway
var <%= "achool#{schoolnumber}name" %> = "N/A";
var <%= "school#{schoolnumber}number" %> = 0;
<% end %>
<% end %>

/dashboard.js
//data for the chart, received from the generated html variables
var data = [
{
value: school1number,
color:"#F7464A",
highlight: "#FF5A5E",
label: school1name
},
{
value: school2number,
color: "#46BFBD",
highlight: "#5AD3D1",
label: school2name
},
{
value: school3number,
color: "#FDB45C",
highlight: "#FFC870",
label: school3name
},
{
value: school4number,
color: "#1919FF",
highlight: "#3030FF",
label: school4name
},
{
value: school5number,
color: "#FF9900",
highlight: "#FFA319",
label: school5name
}
]


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *