Screencast: Diagramme in Rails Applikationen verwenden

Bilder sagen mehr tausend Worte und daher werden oft Diagramme zur Visualisierung von Daten eingesetzt. Ryan zeigt diese Woche wie Highchart für Diagramme und Grafen innerhalb einer Railsapplikation eingesetzt werden kann.

 

Download:

Download(29.1 MB, 16:12)
Alternativer Download für iPod & Apple TV(27.4 MB, 16:12)

 

Resourcen:

 

Quellcode:

[html]
<!– layouts/application.html.erb –>
<%= javascript_include_tag "jquery-1.4.2.min", "rails", "highcharts" %>

<!– orders/index.html.erb –>
<script type="text/javascript" charset="utf-8">
$(function() {
new Highcharts.Chart({
chart: {
renderTo: "orders_chart"
},
title: {
text: "Orders by Day"
},
xAxis: {
type: "datetime"
},
yAxis: {
title: {
text: "Dollars"
}
},
tooltip: {
formatter: function() {
return Highcharts.dateFormat("%B %e, %Y", this.x) + ‚: ‚ +
"$" + Highcharts.numberFormat(this.y, 2);
}
},
series: [
<% { "Download" => Order.download, "Shipping" => Order.shipping }.each do |name, orders| %>
{
name: "<%= name %>",
pointInterval: <%= 1.day * 1000 %>,
pointStart: <%= 3.weeks.ago.to_i * 1000 %>,
data: <%= orders_chart_series(orders, 3.weeks.ago) %>
},
<% end %>
]
});
});
</script>
<div id="orders_chart" style="width:560px; height:300px;"></div>
[/html]

[ruby]
# rails c
Order.group("date(purchased_at)").select("purchased_at, sum(total_price) as total_price").first.total_price.to_f
Order.group("date(purchased_at)").select("purchased_at, sum(total_price) as total_price").first.purchased_at.to_date

# models/order.rb
scope :shipping, where(:shipping => true)
scope :download, where(:shipping => false)

def self.total_on(date)
where("date(purchased_at) = ?", date).sum(:total_price)
end

# orders_helper.rb
def orders_chart_series(orders, start_time)
orders_by_day = orders.where(:purchased_at => start_time.beginning_of_day..Time.zone.now.end_of_day).
group("date(purchased_at)").
select("purchased_at, sum(total_price) as total_price")
(start_time.to_date..Date.today).map do |date|
order = orders_by_day.detect { |order| order.purchased_at.to_date == date }
order && order.total_price.to_f || 0
end.inspect
end
[/ruby]

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.

Diese Website verwendet Akismet, um Spam zu reduzieren. Erfahre mehr darüber, wie deine Kommentardaten verarbeitet werden.