之前已经介绍了一些关于Gruff的基础知识和应用,当然gruff的图表是生成的,当时生产,就存在缓存的问题。那么,我们看一个Gruff缓存的例子:
[b]
1. 安装插件[/b]
[b]2. Rails中进行配置 [/b]
[b]3. 在Controller的调用[/b]
[b]4. 在model中进行cache[/b]
[b]5. Html的显示[/b]
[b]6. 生成效果如下[/b]
[img]/upload/attachment/131711/0ab5b269-07de-3e92-ac7c-5d6774afcca6.png[/img]
[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]