Class: DbMod::Statements::Configuration::As::Csv

Inherits:
Object
  • Object
show all
Defined in:
lib/db_mod/statements/configuration/as/csv.rb

Overview

Coercer which converts an SQL result set into a string formatted as a CSV document. May be enabled for a prepared method or statement method using .as(:csv):

def_statement(:a, 'SELECT a, b FROM foo') { as(:csv) }
def_prepared(:b, 'SELECT b, c FROM bar') { as(:csv) }

def do_stuff
  a # => "a,b\r\n1,2\r\n3,4\r\n..."
end

Class Method Summary collapse

Class Method Details

.call(results) ⇒ String

Formats the results as a CSV document using the column names from the result set.

Parameters:

  • results (Object)

    SQL result set

Returns:

  • (String)

    a CSV formatted document



22
23
24
25
26
27
28
29
30
31
# File 'lib/db_mod/statements/configuration/as/csv.rb', line 22

def self.call(results)
  headers = nil
  CSV.generate do |csv|
    results.each do |row|
      csv << (headers = row.keys) unless headers

      csv << headers.map { |col| row[col] }
    end
  end
end