乐者为王

Do one thing, and do it well.

在Rails中使用Open Flash Chart II

今天我们讲如何用Rails结合Open Flash Chart II(以下简称OFC2)实现如下的图表:

在项目中安装OFC2插件,生成相关controller:

1
2
script/plugin install git://github.com/pullmonkey/open_flash_chart.git
script/generate controller stats index

在生成的app/controllers/stats_controller.rb中添加以下代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class StatsController < ApplicationController
  def index
    @graph = open_flash_chart_object(500, 300, "/stats/graph_code")
  end

  def graph_code
    title = Title.new("Glass Bar")

    bar = BarGlass.new
    bar.set_values([-1,2,3,7,8,-7.3])

    y = YAxis.new
    y.set_range(-10, 10, 5)

    chart = OpenFlashChart.new
    chart.y_axis = y
    chart.set_title(title)
    chart.add_element(bar)
    render :text => chart.to_s
  end
end

在config/routes.rb中添加路由:

1
match 'stats/graph_code' => 'stats#graph_code'

将插件中的assets/javascripts/swfobject.js拷贝到public/javascripts目录下(可以看到该目录下已经有两个open-flash-chart开头的swf文件,如果没有的话,需要从插件中拷过来)。在相应的app/views/stats/index.html中添加如下代码:

1
2
3
<script src="/javascripts/swfobject.js" type="text/javascript"></script>

<%= @graph %>

Comments