40% off your First Order with GoDaddy.com!

Jul 6, 2009

Dynamic Stat Graphs in Rails

What started out as a ‘quick feature’ turned out to be a fun Ruby endeavor – below is a guide with some neat Ruby tricks to create dynamic stat graphs (sample above) with the help of Gruff library. In my visual database explorer article I talked about generating SVG graphs with the help of Scruffy. However, SVG is a nightmare when it comes to browser compatibility issues and inline support, hence in this instance we will settle for RMagick on the backend.

First off, if you haven’t already, take a look at the Gruff RDoc – there is a lot of features hidden under the covers! Assuming you have the gem and the plugin installed, let’s get right to it. First the code, then the explanations:

First few lines should be self-explanatory, we specify custom geometry, our theme colors, hide the title, and finally indicate the font we would like to use in the image. (Note: If RMagick complains about being unable to measure the font-sizes, make sure you have ‘freetype-fonts’ installed on your system) Next, is the SQL aggregation code, here we want to count the number of new users, votes and bookmarks on monthly basis:

There is one catch, if we have no new records in one of the intervals, than the count will be missing from the returned OrderedHash – we need to guard against this by injecting ‘0′ counts for the missing intervals:

Almost done. After assigning the x-axis labels we call send_data to stream the resulting PNG image directly to the browser. Now all we have to do is embed our image into a page, or call it directly:

After adding a quick CSS border and centering the image, you can feast your eyes on the latest trends of your paradigm-shifting application. For performance reasons, I would also recommend caching the action if you plan to display your results in a high-traffic area. For my personal use, I am only showing the trends in a private administration section (shown on the left) – I can afford to regenerate the image on every refresh. For more ideas and Ruby graphing tutorials take a look at: Visual Database Explorer and Dynamic Graphics in Rails 2.2.

No comments:

Post a Comment