Sha256: dda88631fbb9264c991044bd01f280ad174910e8b90808a03ab6468341985467

Contents?: true

Size: 890 Bytes

Versions: 16

Compression:

Stored size: 890 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

      add_headers(headers) if headers

      generate(&block) if block
    end

    def generate
      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

16 entries across 16 versions & 1 rubygems

Version Path
csv-utils-0.3.24 lib/csv_utils/csv_report.rb
csv-utils-0.3.23 lib/csv_utils/csv_report.rb
csv-utils-0.3.22 lib/csv_utils/csv_report.rb
csv-utils-0.3.21 lib/csv_utils/csv_report.rb
csv-utils-0.3.20 lib/csv_utils/csv_report.rb
csv-utils-0.3.19 lib/csv_utils/csv_report.rb
csv-utils-0.3.18 lib/csv_utils/csv_report.rb
csv-utils-0.3.17 lib/csv_utils/csv_report.rb
csv-utils-0.3.16 lib/csv_utils/csv_report.rb
csv-utils-0.3.15 lib/csv_utils/csv_report.rb
csv-utils-0.3.14 lib/csv_utils/csv_report.rb
csv-utils-0.3.13 lib/csv_utils/csv_report.rb
csv-utils-0.3.12 lib/csv_utils/csv_report.rb
csv-utils-0.3.11 lib/csv_utils/csv_report.rb
csv-utils-0.3.10 lib/csv_utils/csv_report.rb
csv-utils-0.3.9 lib/csv_utils/csv_report.rb