Class: CloudXLS::CSVWriter

Inherits:
Object
  • Object
show all
Defined in:
lib/cloudxls-rails/csv_writer.rb

Constant Summary collapse

DATETIME_FORMAT =
"%FT%T.%L%z".freeze
DATE_FORMAT =
"%F".freeze

Class Method Summary collapse

Class Method Details

.enumerator(scope, options = {}) ⇒ Enumerator

Example

Post.csv_enumerator(Post.all, [:title, :author, :published_at])

Parameters:

  • scope (ActiveRecord::Scope)

    An activerecord scope object for the records to be exported. Example: Post.all.limit(500).where(author: “foo”)

Returns:

  • (Enumerator)

    enumerator to use for streaming response.



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/cloudxls-rails/csv_writer.rb', line 48

def self.enumerator(scope, options = {})
  columns = options[:columns]

  Enumerator.new do |row|
    if options[:skip_headers] != true
      if scope.respond_to?(:column_names)
        columns ||= scope.column_names
      end
      if columns
        row << csv_titles(columns, :titleize).to_csv
      end
    end

    enum = scope_enumerator(scope)
    scope.send(enum) do |record|
      row << csv_row(record, columns).to_csv
    end
  end
end

.text(scope, options = {}) ⇒ String

Generates CSV string.

Parameters:

  • columns (Array<String/Symbol>)

    Method/attribute keys to for the export.

Returns:

  • (String)

    The full CSV as a string. Titleizes columns for the header.



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

def self.text(scope, options = {})
  columns = options[:columns]

  str = ::CSV.generate do |csv|

    if options[:skip_headers] != true
      if scope.respond_to?(:column_names)
        columns ||= scope.column_names
      end
      if columns
        csv << csv_titles(columns, :titleize)
      end
    end

    enum = scope_enumerator(scope)
    scope.send(enum) do |record|
      csv << csv_row(record, columns)
    end
  end
  str.strip!
end