Jan
17

thegiive又贡献了一篇非常有用的文章,收藏分享:Faster CSV:做報表的好幫手

FasterCSV 是 Ruby 當中一個處理 CSV 檔案的 lib。顧名思義,他做 CSV 處理速度比 Ruby standard Lib 快。這裡介紹怎麼連結 Active Record 產生報表,並且每天寄一份 Email 報表給管理者。本篇參考自How to email reports from Rails

安裝

gem i fastercsv

即安裝完成,要在程式使用請先 require

require ‘rubygems’
require ‘faster_csv’

跟 Active Record 連結,並且產生報表

我們假設我們想要把 User 資料庫裡面的東西作成 CSV 檔案

FasterCSV.open(“report.csv”, “w”) do |csv|
fields  = User.content_columns.inject([]) do |result,column|
result << column.name
end
csv << fields.map {|f| f.titleize }
User.find_all.each do |row|
csv <<  fields.map {|f| row[f] }
end
end
其中 csv << 代表塞入一次塞一行,如果還沒做好之前,先用一個 Array 來暫存。最後在用csv << temp_array 來塞入比較好。

如果寄 Email 報表我就直接用How to email reports from Rails 的範例。
 
class Notifier < ActionMailer::Base
def sales_for_yesterday
  require ‘FasterCSV’
  @from = ’someone@example.com
  @recipients = ’someone@example.com
  @sent_on = Time.now
  @yesterday = 1.day.ago
  @body = { :yesterday => @yesterday }
  @subject = “Sales Report”
  attachment :content_type => “text/csv”, :filename => “sales_#{@yesterday.to_date}.csv” do |a|
    a.body = FasterCSV.generate do |csv|
      csv < < (fields = [“artist”, “product”, “variant”, “unit price”, “qty sold”, “total”]).map {|f| f.titleize }
      Report.sales_for_date(@yesterday).each do |row|
        csv << fields.map {|f| row[f] }
      end
    end
  end
end
end
其中這段是代表附帶一份檔案,並且 a.body assign 給剛剛產生的 CSV Object 即可
 
attachment :content_type => “text/csv”, :filename => “file_name.csv” do |a|
    a.body = FasterCSV.generate do |csv|
# 填入剛剛的 code 即可
    end
end
 
至於中間,就填入剛剛寫的跟 Active Record 連結的 code 即可。

至於要每天寄一份 Email 報表,請用 Crontab + Rails 裡面的 Runner 即可。 

Link to Faster CSV:做報表的好幫手

Share and Enjoy:These icons link to social bookmarking sites where readers can share and discover new web pages.
  • del.icio.us
  • digg

Tags:

No Responses

Leave a Response

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>