Sha256: 42f9984686b5d9e8a1f6a868db6305cf07954d10e93ff3bb1b89a764df515313

Contents?: true

Size: 911 Bytes

Versions: 1

Compression:

Stored size: 911 Bytes

Contents

# Builds a csv file from csv rows
module CSVUtils
  class CSVReport
    attr_reader :csv,
                :must_close

    def initialize(csv, headers = nil, csv_options = {}, &block)
      @csv =
        if csv.is_a?(String)
          @must_close = true
          mode = csv_options.delete(:mode) || 'wb'
          CSV.open(csv, mode, csv_options)
        else
          @must_close = false
          csv
        end

      generate(headers, &block) if block
    end

    def generate(headers = nil)
      add_headers(headers) if headers
      yield self
      close if @must_close
    end

    def append(csv_row)
      @csv <<
        if csv_row.is_a?(Array)
          csv_row
        else
          csv_row.to_a
        end
    end
    alias << append

    def add_headers(csv_row)
      append(csv_row.is_a?(Array) ? csv_row : csv_row.csv_headers)
    end

    def close
      @csv.close
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
csv-utils-0.3.7 lib/csv_utils/csv_report.rb