This adds a CsvSerializable module which is mixed into Array,
ActiveRecord::NamedScope::Scope, and adds functionality to
ActiveRecord::Base implementing the to_csv method.

On Array, and ActiveRecord::NamedScope::Scope this method will call
"to_csv_header" on the class of the first element of the array to get the
header, and then "to_csv" on each element. If a block is given, each line will
be yielded to the block, otherwise, the lines will be concatenated and
returned.

With ActiveRecord::Base:

 * #to_csv will export the values provided by Model#to_csv_array.

 * Model#to_csv_array defaults to the values of each property specified by
   Model::to_csv_properties.

 * Model::to_csv_properties defaults to the column names of the model table.

 * Model::to_csv_header defaults to using Model::to_csv_properties as the
   header.

Paired-With: Daniel Pittman
Paired-With: Jacob Helwig <[email protected]>
Signed-off-by: Nick Lewis <[email protected]>
---
Local-branch: ticket/next/7007
 config/initializers/requires.rb |    1 +
 lib/csv_extensions.rb           |   42 +++++++++++++++++++++++++++++++++++++++
 2 files changed, 43 insertions(+), 0 deletions(-)
 create mode 100644 lib/csv_extensions.rb

diff --git a/config/initializers/requires.rb b/config/initializers/requires.rb
index 067365e..57ec8ca 100644
--- a/config/initializers/requires.rb
+++ b/config/initializers/requires.rb
@@ -4,3 +4,4 @@ require "#{RAILS_ROOT}/lib/association_collection_dependent"
 require "#{RAILS_ROOT}/lib/has_parameters"
 require "#{RAILS_ROOT}/lib/active_model_scopes"
 require "#{RAILS_ROOT}/lib/puppet/report"
+require "#{RAILS_ROOT}/lib/csv_extensions"
diff --git a/lib/csv_extensions.rb b/lib/csv_extensions.rb
new file mode 100644
index 0000000..eb254d9
--- /dev/null
+++ b/lib/csv_extensions.rb
@@ -0,0 +1,42 @@
+require 'csv'
+
+module CsvSerializable
+  def to_csv(&blk)
+    header = first.class.to_csv_header if 
first.class.respond_to?(:to_csv_header)
+    if blk
+      yield header + "\n" if header
+      each {|x| yield x.to_csv + "\n"}
+      nil
+    else
+      lines = map(&:to_csv)
+      lines.unshift header if header
+      lines.join("\n")
+    end
+  end
+end
+
+class Array
+  include CsvSerializable
+end
+
+class ActiveRecord::NamedScope::Scope
+  include CsvSerializable
+end
+
+class ActiveRecord::Base
+  def self.to_csv_properties
+    column_names
+  end
+
+  def self.to_csv_header
+    CSV.generate_line to_csv_properties
+  end
+
+  def to_csv_array
+    self.class.to_csv_properties.map {|prop| self.send(prop)}
+  end
+
+  def to_csv
+    CSV.generate_line to_csv_array
+  end
+end
-- 
1.7.5.1

-- 
You received this message because you are subscribed to the Google Groups 
"Puppet Developers" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/puppet-dev?hl=en.

Reply via email to