class TableStructure::Iterator

Public Class Methods

new( schema, header: { context: nil, step: nil }, row_type: :array ) click to toggle source
# File lib/table_structure/iterator.rb, line 29
def initialize(
  schema,
  header: { context: nil, step: nil },
  row_type: :array
)
  @table = Table.new(schema, row_type: row_type)
  @header_options = HeaderOptions.new(header)
end

Public Instance Methods

iterate(items, &block) click to toggle source
# File lib/table_structure/iterator.rb, line 38
def iterate(items, &block)
  raise ::TableStructure::Error, "Must be enumerable. #{items}" unless items.respond_to?(:each)

  table_enum = ::Enumerator.new do |y|
    body_enum = @table.body(items)

    if @header_options.enabled?
      header_row = @table.header(context: @header_options.context)
      y << header_row

      if @header_options.step
        loop do
          @header_options.step.times { y << body_enum.next }
          y << header_row
        end
      else
        body_enum.each { |row| y << row }
      end
    else
      body_enum.each { |row| y << row }
    end
  end

  table_enum = table_enum.lazy.map(&block) if block_given?

  table_enum
end