require 'csv' # == Report # # An initialized Report expects to be passed a block that supplies an array # suitable for CSV conversion. class Report def initialize(title, &block) @title = title @data_ary = yield @data_csv = String.new CSV::Writer.generate(@data_csv) do |csv| @data_ary.each { |data| csv << data } end end # Create a new report def self.create(*args, &block) puts "Building report for #{args.first}..." self.send(:new, args.first, &block).write! end private def write! file_name = @title.gsub(/ /, '_').downcase file_path = File.join( File.dirname(__FILE__),"reports", "#{file_name}.csv") File.open(file_path, "w") do |file| @data_csv.each_line { |line| file << line } end end end # == Array # # Some utility extentions to the Array class class Array def extract(method) map { |e| e.send(method) } end # The sum of all elements in the array. def sum inject( 0 ) { |sum, x| sum + (x.nil? ? 0 : x) } end # The mean of all elements in the array. def mean (size > 0) ? sum.to_f / size : 0 end end