Class: TableStructure::Writer

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

Defined Under Namespace

Classes: Output

Instance Method Summary collapse

Constructor Details

#initialize(schema, header_omitted: false, header_context: nil, method: :<<, row_type: :array, **deprecated_options) ⇒ Writer

Returns a new instance of Writer.



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/table_structure/writer.rb', line 5

def initialize(
  schema,
  header_omitted: false,
  header_context: nil,
  method: :<<,
  row_type: :array,
  **deprecated_options
)
  if deprecated_options.key?(:result_type)
    warn '[TableStructure] `:result_type` option has been deprecated. Use `:row_type` option instead.'
    row_type = deprecated_options[:result_type]
  end

  @schema = schema
  @options = {
    header_omitted: header_omitted,
    header_context: header_context,
    method: method,
    row_type: row_type
  }
end

Instance Method Details

#write(items, to:, method: @options[:method], header_omitted: @options[:header_omitted], header_context: @options[:header_context], row_type: @options[:row_type], **deprecated_options, &block) ⇒ Object



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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/table_structure/writer.rb', line 27

def write(
  items,
  to:,
  method: @options[:method],
  header_omitted: @options[:header_omitted],
  header_context: @options[:header_context],
  row_type: @options[:row_type],
  **deprecated_options,
  &block
)
  if deprecated_options.key?(:result_type)
    warn '[TableStructure] `:result_type` option has been deprecated. Use `:row_type` option instead.'
    row_type = deprecated_options[:result_type]
  end

  items = enumerize(items)

  header_options =
    if header_omitted
      false
    else
      { context: header_context }
    end

  @schema.create_table(row_type: row_type) do |table|
    output = Output.new(to, method: method)

    enum =
      Table::Iterator
      .new(
        table,
        header: header_options
      )
      .iterate(items)

    if block_given?
      enum =
        enum
        .lazy
        .map { |row| block.call(row) }
    end

    enum.each { |row| output.write(row) }
  end
  nil
end