Skip to content

Instantly share code, notes, and snippets.

@taiansu
Created December 15, 2012 19:05
Show Gist options
  • Save taiansu/4298235 to your computer and use it in GitHub Desktop.
Save taiansu/4298235 to your computer and use it in GitHub Desktop.
CashNotes' chart with Morris.js
<!DOCTYPE html>
<html>
<head>
<%# ... %>
<%= include_gon %>
<%= yield :head %>
</head>
<%# ... %>
</html>
//= require raphael
//= require morris
window.chart_init = ->
Morris.Line({
element: 'records_chart'
data: $('#records_chart').data('records')
xkey: 'date'
ykeys: ['total_amount'].concat(gon.chart_categories)
labels: ['Total_amount'].concat(gon.chart_categories)
preUnits: '$'
})
class CategoriesController < ApplicationController
# ...
def show
#...
gon.chart_categories = @category.title
respond_to do |format|
format.html # show.html.erb
format.json { render json: @category }
end
end
# ...
end
<% content_for :head do %>
<script type="text/javascript">
$(function() {
chart_init();
});
</script>
<% end %>
<%# ... %>
gem 'raphael-rails'
gem 'morrisjs-rails'
gem 'gon'
#...
class Record < ActiveRecord::Base
# ......
def self.total_grouped_by_day(start)
records = where(date: start.beginning_of_day..Time.zone.today)
records = records.group('date(date)')
records = records.select('date, sum(amount) as total_amount')
records = records.group_by{ |r| r.date.to_date}
end
def self.sum_of_category_by_day(start)
records = where(date: start.beginning_of_day..Time.zone.today)
records = records.group('category_id, date(date)')
records = records.select('category_id, date, sum(amount) as total_amount')
records = records.group_by{ |r| r.category_id }
records.map do |category_id, value|
value.group_by {|r| r.date.to_date}
end
end
end
<% content_for :head do %>
<script type="text/javascript">
$(function() {
chart_init();
});
</script>
<% end %>
<%# ... %>
<%= content_tag :div, "", id: "records_chart", data:{records: records_chart_data} %>
class RecordsController < ApplicationController
# GET /records
# GET /records.json
def index
gon.chart_categories = Category.all.map(&:title)
# ...
end
# ...
end
momodule RecordsHelper
def records_chart_data(category = nil, start = 3.weeks.ago)
total_by_day = Record.total_grouped_by_day(start)
category_sum_by_day = Record.sum_of_category_by_day(start)
(start.to_date..Time.zone.today).map do |date|
chart_hash = {
:date => date,
:total_amount => total_by_day[date].try(:first).try(:total_amount) || 0
}
Category.all.each_with_index do |category, index|
chart_hash[category.title] = category_sum_by_day[index][date].try(:first).try(:total_amount) || 0
end
chart_hash
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment