Sha256: de7ce32283163e64311661f736af3f6e372b68b12f07da1bb961a38698abc7a0

Contents?: true

Size: 1021 Bytes

Versions: 1

Compression:

Stored size: 1021 Bytes

Contents

module AsCSV
  class CSVBuilder
    attr_reader :records, :options

    def initialize(records, options={})
      @records = [*records]
      @options = options
    end

    def to_csv
      rows.collect { |row| CSVProxy.generate_line row }.join if valid?
    end

    def rows
      @rows ||= [headers] + data_rows if valid?
    end

    def headers
      @headers ||= csv_hashes.collect(&:keys).flatten.uniq if valid?
    end

    def data_rows
      @data_rows ||= csv_hashes.collect { |csv_hash| data_row csv_hash } if valid?
    end

    def valid?
      csv_hashes.any? && validate_hashes!
    end

    private

      def validate_hashes!
        csv_hashes.each do |hash|
          raise TypeError, "expected as_csv to return Hash" unless hash.is_a? Hash
        end
      end

      def csv_hashes
        @csv_hashes ||= records.collect { |r| r.as_csv(options) if r.respond_to? :as_csv }.compact
      end

      def data_row(csv_hash)
        headers.collect { |header| csv_hash[header] }
      end
  end  
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
as_csv-1.0.2 lib/as_csv/csv_builder.rb