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

Constant Summary collapse

DEFAULT_ORDER_BY =
'id'
DEFAULT_BATCH_SIZE =
1000
PREFIX_REGEX =
/\A[=\+\[email protected];]/.freeze

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.


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

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.


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

def rows_written
  @rows_written
end

Instance Method Details

#render(truncate_after_bytes = nil) ⇒ Object

Renders the csv to a string


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

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


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

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

#statusObject


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

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

#truncated?Boolean

Returns:

  • (Boolean)

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

def truncated?
  @truncated
end