class ResultSet attr_reader :columns attr_reader :hashes def initialize(statement, output_param_names = []) @padding = " " @spacer = " " @columns = statement.columns @hashes = [] if output_param_names.length > 0 apply_output_params output_param_names, statement else extract_results statement end end def apply_output_params(output_param_names, statement) output_param_names.each do |output_param_name| instance_variable_set(output_param_name, statement.fetch![0]) statement.more_results end end def method_missing(name) member_var = eval("@#{name}") if !member_var.nil? return member_var else return super end end def is_output_param?(name) return !eval("#{name}").nil? end def count return @hashes.size end def size return count end def empty? return count == 0 end def collect @hashes.each do |hash| yield hash end end def has?(expected_result_set) return contains?(expected_result_set.row_hashes) end def contains?(*expected_rows) expected_rows.flatten.each do |expected| return false unless contains_row?(expected) end return true end def contains_row?(expected) expected_with_symbols = convert_keys_to_symbols(expected) @hashes.each do |actual| return true if actual == actual.merge(expected_with_symbols) end return false end def to_s column_widths = widest_value_in_columns result = create_header_row(column_widths) result << "\n" + create_separator_row(column_widths) @hashes.each { |row| result << "\n" + create_data_row(row, column_widths) } return result end private def create_separator_row(column_widths) result = "" column_widths.each do |width| result << " " num_bars = width + ( @padding.length * 2 ) num_bars.times { result << "-" } end result << " " return result end def create_header_row( column_widths ) result = "|" column_names.each_with_index do |header, i| result << "#{@padding}" + create_entry(header, column_widths[i]) + "#{@padding}|" end return result end def create_data_row(row, column_widths) result = "|" column_names.each_with_index do |header, i| result << "#{@padding}" + create_entry(row[header.to_sym].to_s, column_widths[i]) + "#{@padding}|" end return result end def create_entry( header, expected_width ) return header if header.length == expected_width num_prefix_spaces = (expected_width - header.length)/2 num_postfix_spaces = expected_width - (num_prefix_spaces + header.length) pre = "" post = "" num_prefix_spaces.times { pre << " " } num_postfix_spaces.times { post << " " } return pre + header + post end def widest_value_in_columns result = [] column_names.each do |header| largest = header.length @hashes.each do |row| if row[header.to_sym].to_s.length > largest largest = row[header.to_sym].to_s.length end end result << largest puts end return result end def column_names return columns.keys end def convert_keys_to_symbols(row) result = {} row.each { |key, value| result[key.to_sym] = value } return result end def extract_results(statement) statement.each_hash { |row| @hashes << convert_keys_to_symbols(row) } end end