Class: TableStructure::Iterator

Inherits:
Object
  • Object
show all
Defined in:
lib/table_structure/iterator.rb

Defined Under Namespace

Classes: HeaderOptions

Instance Method Summary collapse

Constructor Details

#initialize(schema, header: { context: nil, step: nil }, row_type: :array) ⇒ Iterator

Returns a new instance of Iterator.



29
30
31
32
33
34
35
36
# 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

Instance Method Details

#iterate(items, &block) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# 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