RSS Feed  August 28th, 2008

Ruby on Rails - PrettyPrint a Hash on a Web Page

Added: November 28th, 2007 (tagged with: ruby+on+rails)

In the current sprint I am in at work (we try to follow the Scrum guidelines of Agile Programming at Leapfrog Online), I needed to compute a tax report. In Georgia, taxes need to be broken down by County and Tax Type (city, state, educational, MARTA, etc.); and we need to report on how much tax we collected and refunded. So, I run a couple of database queries to get raw numbers back, and I compute cell, row, and column totals in Ruby, saving the values in a hash that I need to format for HTML and CSV.

Now, as I am building the HTML, I want to have the raw hash output at the top of my page so I can ensure I am walking the hash properly. So I use <%= h @results.inspect %> to give me an HTML-encoded string representation of the hash. The output looks something like this:

{"IL"=> {"returns"=>5, "orders"=>80, "COUNTY"=> {"refunded"=> {"TAX_TYPE"=>#<BigDecimal:XXXXXX,'0.1998E1',8(12)>, ... }, "collected"=>{"TAX_TYPE"=>#<BigDecimal:XXXXXX,'0.1998E1',8(12)>, ... } "total"=>#<BigDecimal:XXXXXX,'0.1998E1',8(12)>}}, "totals"=> {"refunded"=>#<BigDecimal:XXXXXX,'0.1998E1',8(12)>, "collected"=>#<BigDecimal:XXXXXX,'0.1998E1',8(12)>, "TAX_TYPE"=>#<BigDecimal:XXXXXX,'0.1998E1',8(12)>, ... }}}, ... }

...a long run-on string nightmare.

What I wanted was something that had structure to it. What I wanted was the structure of pp (PrettyPrint), but in web format. What I ended up with was this: <%= h PP.pp( @results, "" ) %>. When wrapped in a pre tag, the output becomes manageable:

{"IL"=>
  {"returns"=>5,
   "orders"=>80,
   "COUNTY"=>
     {"refunded"=>
       {"TAX_TYPE"=>#<BigDecimal:XXXXXX,'0.1998E1',8(12)>,
        ... },
      "collected"=>
       {"TAX_TYPE"=>#<BigDecimal:XXXXXX,'0.1998E1',8(12)>,
        ... }
      "total"=>#<BigDecimal:XXXXXX,'0.1998E1',8(12)>}},
   "totals"=>
     {"refunded"=>#<BigDecimal:XXXXXX,'0.1998E1',8(12)>,
      "collected"=>#<BigDecimal:XXXXXX,'0.1998E1',8(12)>,
      "TAX_TYPE"=>#<BigDecimal:XXXXXX,'0.1998E1',8(12)>,
       ... }}},
 ... }

© 2006 - 2008 Michael J. Sepcot - michael (dot) sepcot (at) gmail (dot) com