Module: MongoidToCSV

Defined in:
lib/mongoid_to_csv.rb,
lib/mongoid_to_csv/version.rb

Constant Summary collapse

VERSION =
"0.4.0"

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.documents_to_csv(documents, fields = documents.first.class.fields) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/mongoid_to_csv.rb', line 14

def documents_to_csv(documents, fields = documents.first.class.fields)
  doc_class = documents.first.class
  csv_columns = fields.keys - %w{_id created_at updated_at _type}
  header_row = csv_columns.to_csv
  records_rows = documents.map do |record|
    csv_columns.map do |column|
      value = record.send(column)
      value = value.to_csv if value.respond_to?(:to_csv)
      value
    end.to_csv
  end.join
  header_row + records_rows
end

Instance Method Details

#to_csvObject

Return full CSV content with headers as string. Defined as class method which will have chained scopes applied.



8
9
10
# File 'lib/mongoid_to_csv.rb', line 8

def to_csv
  documents_to_csv(all, fields)
end