开发环境:
OS:WindowsXP
Ruby:Ruby1.8.7
Rails:Rails2.3.5
Mysql:Mysql5.0.9
IDE:Rubymine2.0.1
一、创建ProductAggragator,实现数据抽取逻辑,本例中将Product.report_table的部分参数做了动态传参处理
class ProductAggregator #Code here def initialize(options={}) @totalField=options[:totalField] @showField = options[:showField] @userField = options[:userField] @renameField=options[:renameField] @conditions=options[:conditions] end def generateTable @table=Product.report_table(:all,:only=>@showField, :include => { :user => {:only =>@userField } }, :conditions=>@conditions) unless @renameField.empty? replaceColumnName() end unless @totalField.empty? showTotal() end end def replaceColumnName unless @renameField.empty? @renameField.each do|key,value| @table.rename_column(key,value) transferShowField(key,value) end end end def transferShowField(key,value) for i in 0..@showField.length-1 if(@showField[i]==key) @showField[i]=value end end end def showTotal total = {} for i in 0..@showField.length-1 if(i==0) total.store(@showField[i],"Total") elsif(@showField[i]==@totalField) total.store(@showField[i],@table.sigma("price")) else total.store(@showField[i],"") end end @table<<total end end
二、创建BaseController,实现Ruport::Controller应用
class BaseController < Ruport::Controller stage :product_sheet def setup self.data = ProductAggregator.new(:showField=>options[:showFields], :userField=>options[:userFields], :totalField=>options[:totalField], :renameField=>options[:renameField], :conditions=>options[:conditions]).generateTable end #等效于 class HTML < Ruport::Formatter::HTML formatter :html do build :product_sheet do output << textile("h3. Products List") output << data.to_html end end #等效于 class PDF < Ruport::Formatter::PDF formatter :pdf do build :product_sheet do pad(10) { add_text "Products List" } draw_table data end end formatter :csv do build :product_sheet do output << data.to_csv end end end
三、在ProductsController中进行报表输出应用
通过template的指定可动态传递不同的报表打印模板
def save_as_report Ruport::Formatter::Template.create(:simple) do |format| format.page = {:layout => :landscape} format.grouping = {:style => :separated} format.text = {:font_size => 16,:justification => :center} format.table = {:font_size => 10,:heading_font_size => 15,:maximum_width => 720,:width => 720} format.column = {:alignment => :center} format.heading = {:alignment => :center,:bold => true} end #界面传参数 pdf =BaseController.render_pdf(:showFields=>["description","title","price"], :userFields=>["username"], :totalField=>"price", :renameField=>{"description"=>"type","title"=>"name","user.username"=>"user"}, :conditions=>["title like ?","%a%"], :template=>:simple) send_data pdf, :type => "application/pdf", :filename => "products.pdf" end
四、product/index.html.erb中调用报表打印
<%= link_to 'Save As Report', :controller=>"products",:action=>"save_as_report"%>
五、在routes.rb中指明save_as_report方法以get方式调用
#添加,:collection=>{:save_as_report=>:get}表示当遇到save_as_report时,用get方式,否则默认方式将跳转到show.html执行查询 map.resources :products ,:collection => { :save_as_report => :get }
报表打印结果: