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,
  result_type: nil, # TODO: :array
  method: :<<
}.freeze

Instance Method Summary collapse

Constructor Details

#initialize(schema, **options) ⇒ Writer

Returns a new instance of Writer.



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

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

Instance Method Details

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



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

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