File: csv_builder.rb

package info (click to toggle)
gitlab 17.6.5-19
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 629,368 kB
  • sloc: ruby: 1,915,304; javascript: 557,307; sql: 60,639; xml: 6,509; sh: 4,567; makefile: 1,239; python: 406
file content (44 lines) | stat: -rw-r--r-- 1,458 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# frozen_string_literal: true

require 'csv'
require 'tempfile'
require 'zlib'

require_relative "csv_builder/version"
require_relative "csv_builder/builder"
require_relative "csv_builder/single_batch"
require_relative "csv_builder/stream"
require_relative "csv_builder/gzip"

# 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
#
module CsvBuilder
  #
  # * +collection+ - The data collection to be used
  # * +header_to_value_hash+ - A hash of 'Column Heading' => 'value_method'.
  # * +associations_to_preload+ - An array of records to preload with a batch of records.
  # * +replace_newlines+ - default: false - If true, replaces newline characters with a literal "\n"
  #
  # 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.
  def self.new(collection, header_to_value_hash, associations_to_preload = [], replace_newlines: false)
    CsvBuilder::Builder.new(
      collection,
      header_to_value_hash,
      associations_to_preload,
      replace_newlines: replace_newlines
    )
  end
end