-
Notifications
You must be signed in to change notification settings - Fork 0
/
iterator.rb
57 lines (48 loc) · 1.34 KB
/
iterator.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# frozen_string_literal: true
module TableStructure
class Iterator
class HeaderOptions
attr_reader :enabled, :context, :step
alias enabled? enabled
def initialize(options)
@enabled = !!options
if options.is_a?(Hash)
@context = options[:context]
@step = options[:step]
end
end
end
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
def iterate(items, &block)
unless items.respond_to?(:each)
raise ::TableStructure::Error, "Must be enumerable. #{items}"
end
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&.positive?
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
end
end