Skip to content

Commit

Permalink
added the ability to include methods of a has_one or belongs_to assoc…
Browse files Browse the repository at this point in the history
…iation by doing @notes.to_csv(:methods => [{:user => :name}])
  • Loading branch information
arydjmal committed Jul 29, 2008
1 parent 76cda95 commit 9149618
Showing 1 changed file with 37 additions and 4 deletions.
41 changes: 37 additions & 4 deletions lib/to_csv.rb
Expand Up @@ -4,16 +4,49 @@ def to_csv(options = {})
if options[:only]
columns = options[:only].to_a
else
columns = self.first.class.columns.collect {|c| c.name.to_sym} -
options[:except].to_a + options[:methods].to_a
columns = self.first.class.columns.collect {|c| c.name.to_sym} - options[:except].to_a
columns -= [:created_at, :updated_at] unless options[:timestamps] == true
columns -= [:id] unless options[:id] == true
end

# Expand methods, [{:user => [:name, :id]}] => [{:user => :name}, {:user => :id}]
if methods = options[:methods]
methods = methods.collect do |method|
if method.is_a?(Symbol)
method
else
if method[method.keys.first].is_a?(Array)
method[method.keys.first].collect {|association_method| [{method.keys.first => association_method}]}
else
method
end
end
end
columns << methods
end

columns = columns.flatten

output = FasterCSV.generate do |csv|
csv << columns.collect {|c| c} unless options[:header] == false

unless options[:header] == false
csv << columns.collect do |column|
if column.is_a?(Symbol)
column
else
"#{column.keys.first}_#{column[column.keys.first]}"
end
end
end

self.each do |item|
csv << columns.collect {|c| item.send(c)}
csv << columns.collect do |column|
if column.kind_of?(Hash)
item.send(column.keys.first).send(column[column.keys.first])
else
item.send(column)
end
end
end
end

Expand Down

0 comments on commit 9149618

Please sign in to comment.