In this second part to a two-part series on creating reports on the desktop with Ruby-on-Rails, you'll learn how to create GUIs with Ruby and take a look at a sample report. It is excerpted from chapter four of the book Practical Reporting with Ruby and Rails, written by David Berube (Apress; ISBN: 1590599330).
GUIs and More for Desktop Reports - Graphing Team Performance on the Desktop (Page 3 of 4 )
Let's say that Transmegtech Studios is reworking the artificial intelligence in its new strategy game using the graphs created in Chapter 3. However, the graphs were created as PNG files, and the chief executive officer (CEO) of the company does not know how to view PNGs. He wants to be able to click an icon on his desktop and launch an application that lets him view charts by clicking a player in a list. Fortunately, this is reasonably easy to do with FXRuby.
Before you can run this example, you'll need the database from Chapter 3 (shown partially in Listing 3-3). You can download the SQL from http://rubyreporting.com/examples/player_4.sql or from the Source/Downloads area of the Apress web site (http://.www.apress.com), and then import the data using the command mysql -u my_mysql_user -p < player_4.sql.
The code to create a simple desktop application for viewing graphs is shown in Listing 4-3.
Listing 4-3.Desktop Team Performance Grapher (desktop_team_performance_graph.rb)
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 class Event < ActiveRecord::Base belongs_to :play end
FROM events AS e INNER JOIN plays AS p ON e.play_id=p.id WHERE p.game_id='#{game_id_to_analyze}' AND p.player_id='#{player.id}' GROUP BY e.event DESC;"
data = [] Event.find_by_sql(sql).each do |row| bar_chart.data row.event, (row.average_time.to_i/1000) end bar_chart.labels = {0=>'Time'} chart_png_filename = "./player_#{player.id}.png" bar_chart.write(chart_png_filename)
FXApp.instance().create # Note that getApp returns the same FXApp instance # as fox_application references.
FXApp.instance().run
Save this script as desktop_team_performance_graph.rb You can run the script using the following command:
ruby desktop_team_performance_graph.rb
When you run this command, you will see a screen with the text "no data." You can then use the drop-down menus to select a game and a player. The sample database has data only for the Tech Website Baron game. Select that game to see a screen similar to Figure 4-3.
Figure 4-3.Player graph displayed by the GUI
Let's take a look at the important parts of the script.