Gruff和缓存图表

之前已经介绍了一些关于Gruff的基础知识和应用,当然gruff的图表是生成的,当时生产,就存在缓存的问题。那么,我们看一个Gruff缓存的例子:
[b]
1. 安装插件[/b]

sudo gem install gruff 


[b]2. Rails中进行配置 [/b]

Rails::Initializer.run do |config|
config.gem 'gruff', :lib => 'gruff', :version => '0.3.4
end


[b]3. 在Controller的调用[/b]

class GruffController < PortalController   
append_before_filter :load_graph,
:only => [total_orders_graph, :top_sellers_graph]
caches_action :recent_orders_graph, :expires_in => 1.day.to_i

def total_orders_graph
orders_graph = @graph.generate_total_orders
send_data orders_graph.to_blob , :type => 'image/png'
end

private
def load_graph
@graph = Graphs::ClientGraph.new(@CURRENT_CLIENT)
end
end


[b]4. 在model中进行cache[/b]

class Graphs::ClientGraph   
def initialize(client)
@client = client
end

def generate_total_orders
total_orders_graph = Gruff::Bar.new
total_orders_graph.title = "Orders"
dates = working_week
total_orders_graph.labels = Hash[*dates.collect{|date|[dates.index(date), date.strftime("%d %b")]}.flatten]

datasets = []
for date in dates
datasets.push(@client.orders.on_day
(date.beginning_of_day,date.end_of_day).count)
end

total_orders_graph.data(:total_orders,datasets, '#009900')
total_orders_graph.x_axis_label = 'Date'
total_orders_graph.y_axis_label = "Total"
total_orders_graph.hide_legend = true
total_orders_graph
end

private
def working_week
days_in_a_week = 7
dates = []
days_in_a_week.times do |day_value|
date = Date.today - day_value.days
dates.push date if date.wday != 0 && date.wday != 6
end
dates.reverse
end
end



[b]5. Html的显示[/b]

<%= image_tag( url_for(:action => :total_orders_graph, :controller => :client_dashboard), :size => '500x400') -%>



[b]6. 生成效果如下[/b]


[img]/upload/attachment/131711/0ab5b269-07de-3e92-ac7c-5d6774afcca6.png[/img]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值