Created
March 8, 2010 21:15
-
-
Save drush/325760 to your computer and use it in GitHub Desktop.
A helper to convert model arrays into crosstab reports
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Crosstab module for ruby. This class allows you to iterate through an | |
# array of models (rows) and refactor the data to a crosstab format. | |
# This takes one of the columns and makes it your row-key, another column | |
# and makes it column-keys, then sums all cell values where these two | |
# keys interesect. | |
# | |
# Currently only a single column can be used for row-keys and column-keys | |
# but this may be expanded in the future with the addition of 'row grouping' | |
class Crosstab | |
# tab = Crosstab.new(Model.find(:all), :rows => 'region', :cols => 'site', :cells => 'value' ) | |
# TODO V2: tab = Crosstab.new(Model.find(:all), :rows => ['country', 'region'], :cols => 'site', :cells => 'value', :function => 'sum' ) | |
def initialize array, params | |
@rows = params[:rows] | |
@cols = params[:cols] | |
@cells = params[:cells] | |
@function = params[:function] | |
@row_hash = {} | |
@col_hash = {} | |
vals = {} | |
array.each { |obj| | |
raise "Invalid row name, make sure your results have a column/member named '#{@rows}'" if obj[@rows].nil? | |
row_key = "#{obj[@rows]}" | |
col_key = "#{obj[@cols]}" | |
value = obj[@cells] | |
#puts "#{row_key}:#{col_key}=#{value}" | |
@row_hash[row_key] = {} if !@row_hash.key?(row_key) | |
@row_hash[row_key][col_key] = !@row_hash[row_key].key?(col_key) ? value : @row_hash[row_key][col_key] + value | |
@col_hash[col_key] = true if !@col_hash.key?(col_key) | |
#puts "Stored: #{@row_hash[row_key][col_key]}" | |
} | |
end | |
def to_csv | |
#puts "#{@col_hash.keys.length} columns and #{@row_hash.keys.length} rows" | |
puts "Crosstab,#{@col_hash.keys.join(",")}" | |
#puts @row_hash.keys.join(",") | |
@row_hash.keys.each { |r| | |
print "#{r}" | |
@col_hash.keys.each {|c| | |
print ",#{@row_hash[r][c]}" | |
} | |
puts "" | |
} | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment