You may know how create a report in Ruby using the Active Record, but that's only half the battle. Reports aren't any good if the users they're intended for can't read them. This article will explain how to adjust reports so that they're more user-friendly to their intended audience. It is excerpted from chapter four of the book Practical Reporting with Ruby and Rails, written by David Berube (Apress; ISBN: 1590599330).
Creating Reports on the Desktop - Creating a Spreadsheet Report (Page 3 of 4 )
Let's say that your manager at Transmegtech Studios, the fictional game development company we've used for the examples in previous chapters, wants a report on the game players' win/loss records per game in the form of a formatted spreadsheet. Listing 4-1 shows the script to create a simple Excel report.
class Player < ActiveRecord::Base has_many :plays end class Game < ActiveRecord::Base has_many :plays end class Play < ActiveRecord::Base belongs_to :game belongs_to :player end
win_count = Play.count(:conditions=>[ "player_id = ? AND game_id= ? AND won=true",
player.id, game.id])
loss_count = Play.count(:conditions=>[ "player_id = ? AND game_id= ? AND won=false",
player.id, game.id])
worksheet.write(current_row, 0, [game.name, win_count, loss_count]) current_row=current_row+1 end
end
workbook.close
Save this code as spreadsheet_team_performance.rb. You can run it by issuing the following command:
ruby spreadsheet_team_perfomance.rb
The script creates a file called spreadsheet_report.xls. Open the file with Microsoft Excel or OpenOffice.org, as shown in Figure 4-1.
Figure 4-1.Player win/loss spreadsheet in OpenOffice.org
Tip You can use the spreadsheet/excel library to create spreadsheets dynamically in a Rails application, and then send them to the user. This lets you have a "Download this as Excel" link in your views, for example. You can see a scheme for quickly sending binary files in Rails at http://wiki.rubyonrails. org/rails/pages/HowtoSendFilesFast.