A simple Mongoid::Base to_csv() class method that preserves scopes. to_csv() returns the entire contents including the header ready to be written to file.
# Assuming a Movie model with title and director_id columns. Movie.to_csv # would return: title,director_id title,director_id Black Swan,0 Inception,1 The Fighter,2 The King's Speech,3 The Kids Are All Right,4 Movie.bad.to_csv # would return: title,director_id The Kids Are All Right,4
For normal arrays, `to_mongoid_csv` works the same way.
Movie.all.mongoid_to_csv # Same as Movie.to_csv
Why not Array.to_csv?
require 'csv' module ArrayToCSV def to_csv if first.is_a?(Mongoid::Document) MongoidToCSV.documents_to_csv(self) else super end end end Array.send :include, ArrayToCSV
Something is giving ruby's internal `Array#to_csv` precedence and ignoring mine. Got tired of messing around with it.
After a model object's attributes are collected, to_csv is called on the resulting array. However, this poses a problem because it will blindly convert the attributes to a string – i.e. call to_s on them. If one of your attributes is a Date, then calling to_s may produce unwanted output. For example, if you have Date::DATE_FORMATS = '%d %B, %Y' your dates will have the month written out like 'January', 'February', etc. To counter this, this gem will make an attempt to call to_csv() on each attribute. To get YYYY-MM-DD output, you could do something like:
class Date def to_csv strftime('%Y-%m-%d') end end
Note that object.send(attribute_name) is used, so datetime fields will be returned as ActiveSupport::TimeWithZone objects.
Options to specify columns to be included (currently, id and timestamp columns are excluded).
Combine with active_record_to_csv somehow since they are essentially doing the same thing.
Tested with Ruby 1.9.2-p318 and Mongoid v2.0.2
If you are using a lower version of Ruby 1.9.2-p318 (the p318 is important), you need to install and require the `faster_csv` gem. This was tested with faster_csv v1.5.4.