== CsvPirate Easily create CSVs of any data that can be derived from your models. CsvPirate is the easy way to create a CSV of essentially anything in Rails, in full pirate regalia. It works better if you are wearing a tricorne! CsvPirate only works for commissions of swag OR grub! Initialize method (a.k.a new()) takes a hash of params: # CsvPirate only works for commissions of swag OR grub! # :swag the ARrr collection of swag to work on (optional) # :grub the ARrr class that the spyglasses will be used on (optional) # :spyglasses named scopes in your model that will refine the rows in the CSV according to conditions of the spyglasses, # and order them according to the order of the spyglasses (optional) # :booty booty (columns/methods) on your model that you want printed in the CSV, also used to create the figurehead (CSV header) # :chart name of directory where you want to hide your loot # :wagonner name of document where you will give detailed descriptions of the loot # :aft filename extention ('.csv') # :shrouds CSV column separator, default is ','. For tsv, tab-delimited, "\t" # :chronometer keeps track of when you hunt for treasure # :gibbet filename spacer after the date, and before the iterative counter/timestamp. MuST contain a '.' # :swab can be :counter, :timestamp, or :none # :counter - default, each successive run will create a new file using a counter # :timestamp - each successive run will create a new file using a HHMMSS time stamp # :none - no iterative file naming convention, just use waggoner and aft # :mop can be :clean or :dirty (:overwrite or :append) (only has an effect if :swab is :none) since overwriting is irrelevant for a new file # :clear - do not use :counter or :timestamp, and instead overwrite the file # :dirty - do not use :counter, or :timestamp, or :overwrite. Just keep adding on. # There are others too, check the source for a complete picture! The create method has the same parameters, and actually creates the CSV. Avast! Here be pirates! To brush up on pirate coding naming conventions: http://www.privateerdragons.com/pirate_dictionary.html Perhaps the next version will have CSV importing abilities... == On The Web Source: http://github.com/pboling/csv_pirate Release Announcement: http://galtzo.blogspot.com/2009/03/csv-pirate.html == Installation Gem Using Git building from source: mkdir -p ~/src cd ~/src git clone git://github.com/pboling/csv_pirate.git cd csv_pirate gem build csv_pirate.gemspec sudo gem install csv_pirate-2.0.1.gem # (Or whatever version gets built) Then cd to your rails app to optionally freeze the gem into your app: rake gems:freeze GEM=csv_pirate Installing Gem from Github's Gem Server: sudo gem install pboling-csv_pirate -s http://gems.github.com Plugin using Git: ruby script/plugin install git://github.com/pboling/csv_pirate.git == Example & Usage Assuming a Make (as in manufacturers of automobiles) model like this: # == Schema Information # # Table name: makes # # id :integer(4) not null, primary key # name :string(255) # factory :string(255) # sales :integer(4) # class Make < ActiveRecord::Base has_many :vehicle_models named_scope :factory_in_germany, :conditions => ["factory = ?", "Germany"] has_csv_pirate_ship :spyglasses => [:factory_in_germany], :booty => [:id, :name] end To create a csv of the names and ids of makes with factories in germany and return the text of the export: Make.walk_the_plank # Get it? HA! If you can't believe I wrote this whole thing JUST to be able to make jokes like that... check ma sources :) The name of the csv that comes out will be (by defualt located in log directory): Make.20090930.export.13.csv Where Make is the class, 20090930 is today's date, .export is the gibbet, and 13 is the iterative file counter, meaning I've run this export 13 times today. All of those filename parts are customizable to a degree. You can also customize the CSV, for example if you want to add a column to the csv: Make.walk_the_plank({:booty => [:id, :name, :sales]}) Youw want a timestamp file counter instead of the integer default: Make.walk_the_plank({:booty => [:id, :name, :sales], :spyglasses => [:all], :swab => :timestamp}) If you want to append each export to the end of the same file (on a per day basis): Make.walk_the_plank({:booty => [:id, :name, :sales], :spyglasses => [:all], :swab => :none, :mop => :dirty}) If you want to restrict the csv to a particular set of named scopes: Make.walk_the_plank({:booty => [:id, :name, :sales], :spyglasses => [:with_abs, :with_esc, :with_heated_seats]}) If you want to create a tsv (tab-delimited) or psv (pipe-delimited) instead of a csv: Make.walk_the_plank({:booty => [:id, :name, :sales], :shrouds => '\t'}) Make.walk_the_plank({:booty => [:id, :name, :sales], :shrouds => '|'}) If you have a method in the Make class like this: def to_slug "#{self.name}_#{self.id}" end getting it in the CSV is easy peasy: Make.walk_the_plank({:booty => [:id, :name, :to_slug]}) If you want to traverse Active Record Associations, or call a method on the return value of another method (unlimited nesting): Make.walk_the_plank({:booty => [:id, :name, :to_slug, {:to_slug => :hash}]}) #will call .hash on the result of make.to_slug Make.walk_the_plank({:booty => [:id, :name, :to_slug, {:to_slug => {:hash => :abs}}]}) #returns make.to_slug.hash.abs Add whatever methods you want to the :booty array. Write new methods, and add them! Make lots of glorious CSVs full of data to impress the pointy ones in the office. You can also use the raw CsvPirate class itself directly wherever you want. The following two sets of code are identical: csv_pirate = CsvPirate.new({ :grub => User, :spyglasses => [:active,:logged_in], :waggoner => 'active_users_logged_in', :booty => ["id","number","login","created_at"], :chart => 'log/csv/' }) csv_pirate.hoist_mainstay() # creates CSV file and writes out the rows CsvPirate.create({ :grub => User, :spyglasses => [:active,:logged_in], :waggoner => 'active_users_logged_in', :booty => ["id","number","login","created_at"], :chart => 'log/csv/' })# creates CSV file and writes out the rows Another example using swag instead of grub: users = User.logged_out.inactive csv_pirate = CsvPirate.new({ :swag => users, :waggoner => 'inactive_users_not_logged_in', :booty => ["id","number","login","created_at"], :chart => 'log/csv/' }) csv_pirate.hoist_mainstay() Then if you want to get your hands on the loot immediately: csv_pirate.weigh_anchor() For those who can't help but copy/paste into console and then edit: csv_pirate = CsvPirate.new({:grub => User,:spyglasses => [:active,:logged_in],:waggoner => 'active_users_logged_in',:booty => ["id","number","login","created_at"],:chart => 'log/csv/'}) OR csv_pirate = CsvPirate.new({:swag => users,:waggoner => 'inactive_users_not_logged_in',:booty => ["id","number","login","created_at"],:chart => 'log/csv/'}) == Downloading the CSV You have the same Make class as above, and you have a MakeController: class MakeController < ApplicationController def download_csv send_data Make.say_your_last_words # "utf-8" is default, and uses options from has_csv_pirate_ship end # OR you can customize it just like walk_the_plank def download_csv send_data Make.say_your_last_words("iso-8859-1", {:booty => [:id, :name]}) end end Too easy? I wrote this for two reasons... pirate jokes and to make my life easier. If you need more flexibility then: def download_csv csv_pirate = Make.blindfold send_data csv_pirate.maroon, :type => 'text/csv; charset=iso-8859-1; header=present', :disposition => "attachment; filename=#{csv_pirate.nocturnal}" end == Advanced Example with Nested Methods You have a VehicleModel class and the same Make class as up above: # == Schema Information # # Table name: vehicle_models # # id :integer(4) not null, primary key # name :string(255) # year :integer(4) # horsepower :integer(4) # price :integer(4) # electric :boolean(1) # make_id :integer(4) # class VehicleModel < ActiveRecord::Base belongs_to :make has_csv_pirate_ship :booty => [:id, :name, :year, {:make => :name}, {:tires => {:size => {:width => :inches}}}] def tires; TireSize.new; end end class TireSize # To call an instance method you need to return an instance def size; TireWidth.new; end end class TireWidth # To call a class method you need to return the class object def width; Measurement; end end class Measurement def self.inches; 13; end end Then to create the CSV: a = VehicleModel.walk_the_plank Then check the output from the console: a.weigh_anchor id,name,year,makename,tiressizewidthinches 1,Cavalier,1999,Chevrolet,13 2,Trailblazer,2006,Chevrolet,13 3,Corvette,2010,Chevrolet,13 4,Mustang,1976,Ford,13 5,Lebaron,1987,Chrysler,13 6,Avalon,1996,Toyota,13 => # Joy to recursive code everywhere! ---------------------------------------------------------------------------------- Author: Peter Boling, peter.boling at gmail dot com Copyright (c) 2009 Peter H. Boling of 9thBit LLC, released under the MIT license. See LICENSE for details.