<commit_before>module SqlToCsv
  class Results
    def initialize(results, file = nil, quote_fields = false)
      @query_results = results
      @file = file
      @quote_fields = quote_fields
    end

    def headers
      @headers ||= @query_results.fields
    end

    def header_line
      headers.map { |f| format_header(f) }.join(',')
    end

    def output_filehandle
      @output_filehandle ||= File.new(@file, 'wb')
    end

    def redirect_to_file?
      !@file.nil?
    end

    def print_line(line)
      puts line
      output_filehandle.puts line if redirect_to_file?
    end

    def format_field(field)
      @quote_fields ? "\"#{field}\"" : field
    end

    def format_header(header)
      format_field(header.capitalize)
    end

    def print
      print_line(header_line)

      @query_results.each(cache_rows: false) do |row|
        result_line = []
        headers.each do |header|
          result_line << format_field(row[header])
        end
        print_line(result_line.join(','))
      end
      cleanup
    end

    private

    def cleanup
      output_filehandle.close if redirect_to_file?<commit_msg>Refactor Results#print<commit_after>module SqlToCsv
  class Results
    def initialize(results, file = nil, quote_fields = false)
      @query_results = results
      @file = file
      @quote_fields = quote_fields
    end

    def headers
      @headers ||= @query_results.fields
    end

    def header_line
      headers.map { |f| format_header(f) }.join(',')
    end

    def output_filehandle
      @output_filehandle ||= File.new(@file, 'wb')
    end

    def redirect_to_file?
      !@file.nil?
    end

    def print_line(line)
      puts line
      output_filehandle.puts line if redirect_to_file?
    end

    def format_field(field)
      @quote_fields ? "\"#{field}\"" : field
    end

    def format_header(header)
      format_field(header.capitalize)
    end

    def print
      print_line(header_line)

      @query_results.each(cache_rows: false) do |row|
        result_line = headers.map { |header| format_field(row[header]) }
        print_line(result_line.join(','))
      end
      
      cleanup
    end

    private

    def cleanup
      output_filehandle.close if redirect_to_file?
{'fraction_non_alphanumeric': 0.09208185053380782, 'fraction_numerical': 0.0, 'mean_word_length': 2.4283536585365852, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2068099', 'n_tokens_mistral': 724, 'n_tokens_neox': 703, 'n_words': 161}