Sha256: 469b1e22bd12030054e98b0f4bdd3cf829ce26c326ea91504486a2d3035f0653

Contents?: true

Size: 861 Bytes

Versions: 1

Compression:

Stored size: 861 Bytes

Contents

require "csv"

module Tabler
  class CSV
    attr_reader :data

    def initialize(data)
      @data = data
    end

    # Create a csv string from the data
    #
    def generate(opts={})
      nd = normalized_data
      ::CSV.generate(opts) do |csv|
        # set header row
        csv << nd[:headers]
        nd[:values].each do |row|
          csv << row
        end
      end
    end

    # Creates a hash with a :headers field
    # and a :values field
    #
    def normalized_data
      result = {}
      result[:headers] = data.inject([]) do |h,a|
        a.each { |k,v| h << k unless h.include?(k) }
        h
      end

      result[:values] = data.map do |h|
        row = []
        h.each do |k,v|
          index_of_key = result[:headers].index(k)
          row[index_of_key] = v
        end
        row
      end
      result
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
tabler-0.0.1 lib/tabler/csv.rb