ActiveRecord Exportable
Data portability is an extremely important feature for any software-as-a-service company. At Mobile Commons, we strongly believe that our customers data is their data and work hard to make sure that information is portable. Whether they want to run their own analytics or share data between different software applications, customers can easily export any Mobile Commons data to CSV.
Because this is such a common requirement, we developed a Rails plugin to automatically make any collection of items in our application (text messages, phone calls, donations, profiles, etc) exportable in CSV format.
The main features are:
- Transform an array of exportable records into a whole CSV file. (By default, FasterCSV transforms arrays into a single CSV row.)
- Export a whole table my calling
.to_csvon the ActiveRecord subclass. - By default, export all of an ActiveRecord’s columns except for created_at and updated_at.
- Allow simple customization of exportable columns by overriding the
export_columnsmethod in your ActiveRecord class. - Allow multiple CSV formats by conditionally branching inside the
export_columnsmethod depending on the format parameter. - Override the names of the columns that get exported (defaults is the database column names)
- Allow complete customization of the export by overriding the
to_rowmethod.
The simplest use-case is just calling to_csv on an ActiveRecord model. This will export the contents of entire table to CSV format
The more common scenario is calling it on a collection of ActiveRecord Models:
You can customize which columns are included in the CSV by defining an export_columns function in your model class. The default is every columns except created_at and updated_at:
You can also define multiple output formats for a single model. Just modify your export_columns function to take a format parameter and return different values depending on its value.
You can override any of the column names. This is useful if you use any technical terms and want to “translate” them before exporting for customers (e.g. a column named ‘guid’ might be exported as “Unique ID”).
The code is quite small. You can simply save it as a file called exportable.rb in the lib folder of your Rails project or install it as a Rails Plugin from GitHub
Credit to Bryan Helmcamp and East Media, who wrote the original version for Mobile Commons.

