Sha256: fdd2022e24f30f800b729b798d01cd8d9aad4c6f342f2a354ebf4548d98f0096

Contents?: true

Size: 1.06 KB

Versions: 2

Compression:

Stored size: 1.06 KB

Contents

module DbMod
  module Statements
    module Configuration
      module As
        # 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 Csv
          # Formats the results as a CSV document using the column names
          # from the result set.
          #
          # @param results [Object] SQL result set
          # @return [String] a CSV formatted document
          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
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
db_mod-0.0.6 lib/db_mod/statements/configuration/as/csv.rb
db_mod-0.0.5 lib/db_mod/statements/configuration/as/csv.rb