Class: ActiveRecord::Base

Inherits:
Object
  • Object
show all
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]

Class Method Summary collapse

Instance Method Summary collapse

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(options={})
  tmp_columns = if options[:only]
    options[:only] #only trumps exclude
  else
    self.content_columns.map{|curr_col| curr_col.name } - options[:exclude].map{|curr_col| curr_col.to_s }
  end

  tmp_columns + options[: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(options={})
  self.class.csv_columns(options).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