Class: CsvBuilder

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

Overview

Generates CSV when given a collection and a mapping.

Example:

columns = {
  'Title' => 'title',
  'Comment' => 'comment',
  'Author' => -> (post) { post.author.full_name }
  'Created At (UTC)' => -> (post) { post.created_at&.strftime('%Y-%m-%d %H:%M:%S') }
}

CsvBuilder.new(@posts, columns).render

Direct Known Subclasses

CsvBuilders::SingleBatch

Constant Summary collapse

DEFAULT_ORDER_BY =
'id'.freeze
DEFAULT_BATCH_SIZE =
1000

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(collection, header_to_value_hash) ⇒ CsvBuilder

  • collection - The data collection to be used

  • header_to_hash_value - A hash of 'Column Heading' => 'value_method'.

The value method will be called once for each object in the collection, to determine the value for that row. It can either be the name of a method on the object, or a lamda to call passing in the object.


29
30
31
32
33
34
# File 'lib/csv_builder.rb', line 29

def initialize(collection, header_to_value_hash)
  @header_to_value_hash = header_to_value_hash
  @collection = collection
  @truncated = false
  @rows_written = 0
end

Instance Attribute Details

#rows_writtenObject (readonly)

Returns the value of attribute rows_written


20
21
22
# File 'lib/csv_builder.rb', line 20

def rows_written
  @rows_written
end

Instance Method Details

#render(truncate_after_bytes = nil) ⇒ Object

Renders the csv to a string


37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/csv_builder.rb', line 37

def render(truncate_after_bytes = nil)
  Tempfile.open(['csv']) do |tempfile|
    csv = CSV.new(tempfile)

    write_csv csv, until_condition: -> do
      truncate_after_bytes && tempfile.size > truncate_after_bytes
    end

    if block_given?
      yield tempfile
    else
      tempfile.rewind
      tempfile.read
    end
  end
end

#rows_expectedObject


58
59
60
61
62
63
64
# File 'lib/csv_builder.rb', line 58

def rows_expected
  if truncated? || rows_written == 0
    @collection.count
  else
    rows_written
  end
end

#statusObject


66
67
68
69
70
71
72
# File 'lib/csv_builder.rb', line 66

def status
  {
    truncated: truncated?,
    rows_written: rows_written,
    rows_expected: rows_expected
  }
end

#truncated?Boolean

Returns:

  • (Boolean)

54
55
56
# File 'lib/csv_builder.rb', line 54

def truncated?
  @truncated
end