Sha256: 1c3fdfa8c5f7a291fbac2f9e12cadb7fadde18c04c93615d62d6cd7e5b715929

Contents?: true

Size: 1.17 KB

Versions: 1

Compression:

Stored size: 1.17 KB

Contents

require 'honey_format/row'

module HoneyFormat
  # Represents rows.
  class Rows
    include Enumerable

    # Returns array of cleaned strings.
    # @return [Rows] new instance of Rows.
    # @param [Array] rows the array of rows.
    # @param [Array] columns the array of column symbols.
    def initialize(rows, columns, builder: nil)
      @rows = prepare_rows(Row.new(columns, builder: builder), rows)
    end

    # @yield [row] The given block will be passed for every row.
    # @yieldparam [Row] a row in the CSV file.
    # @return [Enumerator]
    #   If no block is given, an enumerator object will be returned.
    def each(&block)
      @rows.each(&block)
    end

    # Returns rows as array.
    # @return [Array] of rows.
    def to_a
      @rows
    end

    # @return [String] CSV-string representation.
    def to_csv
      to_a.map(&:to_csv).join
    end

    private

    def prepare_rows(builder, rows)
      built_rows = []
      rows.each do |row|
        # ignore empty rows - the Ruby CSV library can return empty lines as [nil]
        next if row.nil? || row.empty? || row == [nil]
        built_rows << builder.build(row)
      end
      built_rows
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
honey_format-0.7.0 lib/honey_format/rows.rb