Class: ActiveRecord::Base
- Inherits:
-
Object
- Object
- ActiveRecord::Base
- Defined in:
- lib/acts_as_csv.rb
Overview
Usage:
Given User is an ActiveRecord model
Options for Model.to_csv, Array.to_csv, and ActionController::Base#send_csv
:only - Array, trumps :exclude. Only these attributes will be included instead of all attributes (things listed in :methods will still be sent)
:only => [ :id, :name, :created_at ]
:methods - Array, additional methods to evaluate and add to the CSV response. Note: you can send nested method calls
:methods => [ :to_s, :complex_method, "my.method.on.a.related.object"]
:exclude - Array, attributes to exclude from CSV result
From ActionController
send_csv User, :only => [:first_name, :email, :created_at] #This will do all records
send_csv User.all(:conditions => ["created_at > ?", some_date]), :only => [:first_name, :email, :created_at]
From ActiveRecord Model
User.to_csv :only => [ :username, :email, :created_at ], :methods => [ :age, "account.id"] # All users additionally get their related Account#id number
User.all(:limit => 10).to_csv :exclude => [:password, :birthdate]
Direct Known Subclasses
Attachment, BookingImport, BookingReference, BookingTemplate, ChargeRate, CivilStatus, Employment, Invoice, LineItem, Note, Person, Product, Religion, Role, Tenant, User
Class Method Summary collapse
-
.csv_columns(options = {}) ⇒ Object
Get the column headers.
-
.to_csv(*args) ⇒ Object
Shortcut for CSV of whole table.
Instance Method Summary collapse
-
#to_csv(options = {}) ⇒ Object
Record to a row level csv array.
Class Method Details
.csv_columns(options = {}) ⇒ Object
Get the column headers
34 35 36 37 38 39 40 41 42 |
# File 'lib/acts_as_csv.rb', line 34 def self.csv_columns(={}) tmp_columns = if [:only] [:only] #only trumps exclude else self.content_columns.map{|curr_col| curr_col.name } - [:exclude].map{|curr_col| curr_col.to_s } end tmp_columns + [:methods].map{|curr_col| curr_col.to_s } end |
.to_csv(*args) ⇒ Object
Shortcut for CSV of whole table
29 30 31 |
# File 'lib/acts_as_csv.rb', line 29 def self.to_csv(*args) find(:all).to_csv(*args) end |
Instance Method Details
#to_csv(options = {}) ⇒ Object
Record to a row level csv array
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
# File 'lib/acts_as_csv.rb', line 45 def to_csv(={}) self.class.csv_columns().map { |curr_col| curr_col = curr_col.to_s #Its a chain of method calls, on intermediary nil, just return nil if !curr_col.index(".") col_val = self.send(curr_col) else col_val = self curr_col.split(".").each {|curr_method| col_val = col_val.send(curr_method) unless col_val.nil?} end col_val.gsub!("\n", " ") if col_val.is_a?(String) # Strip newlines, Appease Excel Gods col_val } end |