Class: TableStructure::Writer

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

Constant Summary collapse

DEFAULT_OPTIONS =
{
  header_omitted: false,
  header_context: nil,
  method: :<<
}.freeze

Instance Method Summary collapse

Constructor Details

#initialize(schema, **options) ⇒ Writer



11
12
13
14
# File 'lib/table_structure/writer.rb', line 11

def initialize(schema, **options)
  @schema = schema
  @options = DEFAULT_OPTIONS.merge(options)
end

Instance Method Details

#write(items, to:, **options) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/table_structure/writer.rb', line 16

def write(items, to:, **options)
  options = @options.merge(options)
  @schema.create_table(**options) do |table|
    unless options[:header_omitted]
      header = table.header(
        context: options[:header_context]
      )
      header = yield header if block_given?
      to.send(options[:method], header)
    end
    table.rows(enumerize(items)).each do |row|
      row = yield row if block_given?
      to.send(options[:method], row)
    end
  end
  nil
end