csv_pirate 5.0.8 → 5.0.9

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,15 @@
1
+ ---
2
+ !binary "U0hBMQ==":
3
+ metadata.gz: !binary |-
4
+ YTQ2MjgzMDM0M2Y5YjI3NTJkYjEzNzA3NTY0ODYwYmY3NGU2YWUxMA==
5
+ data.tar.gz: !binary |-
6
+ M2JlZDFkM2QxZWI3ZmNiYTczMjExYTY1NTYyMjE2Nzk0NmE4OWE5ZA==
7
+ SHA512:
8
+ metadata.gz: !binary |-
9
+ ZWEzZDU0ZmQ4NzdjMWYyOGNiNzljY2VhMmFkYjkwNDM5ZjFjNTY1Yzc3MjY3
10
+ YTQwZTQwNDhlNWZhY2U4YzI2N2U3ZDkyYzRhNzRjM2RhNzI1ZGE5ZmVjMzM2
11
+ Zjk2YmY2YjM3OTkzNDY3MGM4ODBmM2RjYzA3Yzc4NTA3OWVkMjg=
12
+ data.tar.gz: !binary |-
13
+ M2ZlZjc1NzUyZTM4Y2U0MzA0MjNjMjQ3NWQ0ZGVkNTU3ODkzYTIwYWFlZjRi
14
+ NWFkMzFiMjNiMjY1OWQ1MWU4MmNiMmFlODAwNGQ0ZjBiYWYyM2UyYWVkZDk5
15
+ YjY2YjdhYjVlNWVjZGQ0YTg2N2E0NGJkYmYyMjMzZTdlNzZjMGU=
@@ -0,0 +1 @@
1
+ service_name: travis-ci
data/.gitignore CHANGED
@@ -1,4 +1,4 @@
1
- # rcov generated
1
+ # rcov/simplecov/coveralls generated
2
2
  coverage
3
3
 
4
4
  # rdoc generated
@@ -62,3 +62,6 @@ spec/csv/*
62
62
 
63
63
  log
64
64
  .rvmrc
65
+
66
+ # Continuous Integration Artifacts
67
+ gemfiles/*.lock
@@ -0,0 +1 @@
1
+ foss
@@ -0,0 +1 @@
1
+ ruby-1.9.3-p484
@@ -1,6 +1,22 @@
1
1
  language: ruby
2
2
  rvm:
3
- - 2.0.0
3
+ - 1.8.7
4
+ - 1.9.2
4
5
  - 1.9.3
6
+ - 2.0.0
5
7
  - jruby-19mode
6
- - rbx-19mode
8
+ - rbx-2.1.1
9
+ gemfile:
10
+ - gemfiles/Gemfile.activerecord-2.3.x
11
+ - gemfiles/Gemfile.activerecord-3.0.x
12
+ - gemfiles/Gemfile.activerecord-3.1.x
13
+ - gemfiles/Gemfile.activerecord-3.2.x
14
+ - gemfiles/Gemfile.activerecord-4.0.x
15
+ matrix:
16
+ exclude:
17
+ - rvm: 1.8.7
18
+ gemfile: gemfiles/Gemfile.activerecord-4.0.x
19
+ - rvm: 1.9.2
20
+ gemfile: gemfiles/Gemfile.activerecord-4.0.x
21
+ - rvm: 2.0.0
22
+ gemfile: gemfiles/Gemfile.activerecord-2.3.x
data/CHANGELOG CHANGED
@@ -1,3 +1,10 @@
1
+ Version 5.0.9 2013-11-26
2
+ - Added back travis builds for 1.8.7, 1.9.2, and updated to rbx-2.1.1
3
+ - Added coveralls, and badges
4
+ - Updated readme, converted to markdown
5
+ - Added the reek list
6
+ - Tested against ActiveRecord 2.3 - 4.0
7
+
1
8
  Version 5.0.8 2013-08-30
2
9
  - BUGFIX - Fixed MINOR/PATCH/BUILD version values
3
10
  - Removed Ruby 1.8.7 hand holding, added instructions for installation of 'faster_csv' when on 1.8.7
data/LICENSE CHANGED
@@ -1,4 +1,4 @@
1
- Copyright (c) 2008-2012 Peter H. Boling (http://peterboling.com)
1
+ Copyright (c) 2008-2013 Peter H. Boling (http://peterboling.com)
2
2
 
3
3
  MIT License
4
4
 
@@ -0,0 +1,507 @@
1
+ # CsvPirate
2
+
3
+ Easily create CSVs of any data that can be derived from any Ruby object (PORO).
4
+
5
+ | Project | Sanitize Email |
6
+ |------------------------ | ----------------- |
7
+ | gem name | csv_pirate |
8
+ | license | MIT |
9
+ | version | [![Gem Version](https://badge.fury.io/rb/csv_pirate.png)](http://badge.fury.io/rb/csv_pirate) |
10
+ | dependencies | [![Dependency Status](https://gemnasium.com/pboling/csv_pirate.png)](https://gemnasium.com/pboling/csv_pirate) |
11
+ | code quality | [![Code Climate](https://codeclimate.com/github/pboling/csv_pirate.png)](https://codeclimate.com/github/pboling/csv_pirate) |
12
+ | continuous integration | [![Build Status](https://secure.travis-ci.org/pboling/csv_pirate.png?branch=master)](https://travis-ci.org/pboling/csv_pirate) |
13
+ | test coverage | [![Coverage Status](https://coveralls.io/repos/pboling/csv_pirate/badge.png)](https://coveralls.io/r/pboling/csv_pirate) |
14
+ | homepage | [https://github.com/pboling/csv_pirate][homepage] |
15
+ | documentation | [http://rdoc.info/github/pboling/csv_pirate/frames][documentation] |
16
+ | author | [Peter Boling](https://coderbits.com/pboling) |
17
+ | Spread ~♡ⓛⓞⓥⓔ♡~ | [![Endorse Me](https://api.coderwall.com/pboling/endorsecount.png)](http://coderwall.com/pboling) |
18
+
19
+ ## Summary
20
+
21
+ CsvPirate is the easy way to create a CSV of essentially anything in Ruby, in full pirate regalia.
22
+ It works better if you are wearing a tricorne!
23
+
24
+ ## Compatibility
25
+
26
+ * Ruby 1.8.7 (Must also install/require 'faster_csv')
27
+ * Ruby 1.9.2, 1.9.3, and 2.0.0
28
+ * Rails (ActiveRecord) 2, 3, and 4
29
+
30
+ ## Usage
31
+
32
+ Pure Ruby! Doesn't require rails (though it works great with Active Record).
33
+
34
+ My goal is to have it do EVERYTHING it possibly can for me, since almost every project I do needs CSV exports.
35
+
36
+ CsvPirate only works for commissions of `swag` OR `grub`!
37
+
38
+ Initialize method (a.k.a new()) takes a hash of parameters, and creates the blank CSV file, and the instance can be modified prior to writing out to CSV:
39
+
40
+ # CsvPirate only works for commissions of swag OR grub!
41
+ # :swag the ARrr collection of swag to work on (optional)
42
+ # :grub the ARrr class that the spyglasses will be used on (optional)
43
+ # :spyglasses named scopes in your model that will refine the rows in the CSV according to conditions of the spyglasses,
44
+ # and order them according to the order of the spyglasses (optional)
45
+ # :booty booty (columns/methods) on your model that you want printed in the CSV, also used to create the figurehead (CSV header)
46
+ # :chart array of directory names (relative to rails root if using rails) which will be the filepath where you want to hide your loot
47
+ # :waggoner name of document where you will give detailed descriptions of the loot
48
+ # :aft filename extention ('.csv')
49
+ # :shrouds CSV column separator, default is ','. For tsv, tab-delimited, "\t"
50
+ # :chronometer keeps track of when you hunt for treasure
51
+ # :gibbet filename spacer after the date, and before the iterative counter/timestamp. MuST contain a '.'
52
+ # :swab can be :counter, :timestamp, or :none
53
+ # :counter - default, each successive run will create a new file using a counter
54
+ # :timestamp - each successive run will create a new file using a HHMMSS time stamp
55
+ # :none - no iterative file naming convention, just use waggoner and aft
56
+ # :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
57
+ # :clean - do not use :swab above (:counter or :timestamp), and instead overwrite the file
58
+ # :dirty - do not use :swab above (:counter, or :timestamp), and do not overwrite. Just keep adding on.
59
+ # :bury_treasure should we store the csv data as it is collected in an array in Ruby form for later use (true), or just write the CSV (false)?
60
+ # :blackjack Specify how you want your CSV header
61
+ # {:join => '-'} joins the method names called to get hte data for that column with '_' underscores.
62
+ # {:humanize =>'-'} first joins as above, then humanizes the string (this is the default)
63
+ # {:array => ['col1',col2','col3'] Uses the column names provided. If the array's length is less than the booty array's length it reverts to :humanize =>'_'
64
+
65
+ Check the source to see if there anything else hiding in there! (HINT: There a bunch more undocumented options)
66
+
67
+ The create method has the same parameters, and actually writes the data to the CSV.
68
+
69
+ Avast! Here be pirates! Brush up on [pirate coding naming conventions](http://www.privateerdragons.com/pirate_dictionary.html).
70
+
71
+
72
+ ## Install
73
+
74
+ gem install csv_pirate
75
+
76
+ If you are still using Ruby < 1.9 then you will need to add fastercsv to your project.
77
+ FasterCSV became the built-in CSV library in Ruby 1.9, so is *only* required if using an older Ruby.
78
+
79
+ gem 'faster_csv', '>= 1.4.0'
80
+
81
+
82
+ ## Upgrading
83
+
84
+ ### From version prior to 5.0
85
+
86
+ NinthBit::PirateShip::ActMethods has been deprecated in favor of CsvPirate::PirateShip::ActMethods.
87
+ Old API still works for now.
88
+
89
+ ### From version prior to 4.0
90
+
91
+ `:chart` was a string which indicated where you wanted to hide the loot (write the csv file)
92
+ Now it must be an array of directory names. So if you want your loot in "log/csv/pirates/model_name", then chart is:
93
+
94
+ ['log','csv','pirates','model_name']
95
+
96
+ CsvPirate ensures that whatever you choose as your chart exists in the filesystem, and creates the directories if need be.
97
+
98
+
99
+ ## Usage with ActiveRecord
100
+
101
+ What's the simplest thing that will work?
102
+
103
+ class MyClass < ActiveRecord::Base
104
+ has_csv_pirate_ship # defaults to csv of all columns of all records
105
+ end
106
+
107
+ MyClass.blindfold # creates the csv, and returns the CsvPirate instance
108
+ MyClass.walk_the_plank # creates the csv, and returns contents of the exported data (that was written into the csv) (as a string)
109
+ MyClass.land_ho # Does Not create the csv, sets up the CsvPirate instance. You can manipulate it and then call .hoist_mainstay on it to create the csv
110
+
111
+ ## Importing to DB or Ruby objects in memory from CSV
112
+
113
+ Importing abilities are now here! You can dump data to CSV, copy the CSV to wherever, and then import the data in the CSV. Works very well with ActiveRecord.
114
+
115
+ See the weigh_anchor method, added to models with has_csv_pirate_ship defined, for dumping.
116
+ See the raise_anchor method, added to models with has_csv_pirate_ship defined, for importing.
117
+ See the to_memory method to convert the data in a csv or CsvPirate instance object back into Ruby class instances
118
+ with as many attributes as possible set equal to the data from the CSV.
119
+
120
+ ## Usage without ActiveRecord
121
+
122
+ [ See Spec Tests for more Examples! ]
123
+
124
+ Since the defaults assume an active record class you need to override some of them:
125
+
126
+ class Star
127
+ extend CsvPirate::PirateShip::ActMethods
128
+ has_csv_pirate_ship :booty => [:name, :distance, :spectral_type, {:name => :hash}, {:name => :next}, {:name => :upcase}, :star_vowels],
129
+ :spyglasses => [:get_stars]
130
+
131
+ attr_accessor :name, :distance, :spectral_type
132
+
133
+ def initialize(*args)
134
+ @name = args.first[:name]
135
+ @distance = args.first[:distance]
136
+ @spectral_type = args.first[:spectral_type]
137
+ end
138
+
139
+ def star_vowels
140
+ self.name.tr('aeiou', '*')
141
+ end
142
+
143
+ def self.get_stars
144
+ [
145
+ Star.new(:name => "Proxima Centauri", :distance => "4.2 LY", :spectral_type => "M5.5Vc"),
146
+ Star.new(:name => "Rigil Kentaurus", :distance => "4.3 LY", :spectral_type => "G2V"),
147
+ Star.new(:name => "Barnard's Star", :distance => "5.9 LY", :spectral_type => "M3.8V"),
148
+ Star.new(:name => "Wolf 359", :distance => "7.7 LY", :spectral_type => "M5.8Vc"),
149
+ Star.new(:name => "Lalande 21185", :distance => "8.26 LY", :spectral_type => "M2V"),
150
+ Star.new(:name => "Luyten 726-8A and B", :distance => "8.73 LY", :spectral_type => "M5.5 de & M6 Ve"),
151
+ Star.new(:name => "Sirius A and B", :distance => "8.6 LY", :spectral_type => "A1Vm"),
152
+ Star.new(:name => "Ross 154", :distance => "9.693 LY", :spectral_type => "M3.5"),
153
+ Star.new(:name => "Ross 248", :distance => "10.32 LY", :spectral_type => "M5.5V"),
154
+ Star.new(:name => "Epsilon Eridani", :distance => "10.5 LY", :spectral_type => "K2V")
155
+ ]
156
+ end
157
+ end
158
+
159
+
160
+ rails development >a = Star.blindfold
161
+ => #<CsvPirate:0x2209098 @buried_treasure=[], @mop=:clean, @spyglasses=[:get_stars], @swabbie=".3", @booty=[:name, :distance, :spectral_type, {:name=>:hash}, {:name=>:next}, {:name=>:upcase}, :star_vowels], @bury_treasure=false, @swab=:counter, @chronometer=Sun, 04 Oct 2009, @maroon="name,distance,spectral_type,namehash,namenext,nameupcase,star_vowels\nProxima Centauri,4.2 LY,M5.5Vc,971295636,Proxima Centaurj,PROXIMA CENTAURI,Pr*x*m* C*nt**r*\nRigil Kentaurus,4.3 LY,G2V,-231389024,Rigil Kentaurut,RIGIL KENTAURUS,R*g*l K*nt**r*s\nBarnard's Star,5.9 LY,M3.8V,1003964756,Barnard's Stas,BARNARD'S STAR,B*rn*rd's St*r\nWolf 359,7.7 LY,M5.8Vc,429493790,Wolf 360,WOLF 359,W*lf 359\nLalande 21185,8.26 LY,M2V,466625069,Lalande 21186,LALANDE 21185,L*l*nd* 21185\nLuyten 726-8A and B,8.73 LY,M5.5 de & M6 Ve,-886693495,Luyten 726-8A and C,LUYTEN 726-8A AND B,L*yt*n 726-8A *nd B\nSirius A and B,8.6 LY,A1Vm,-969980943,Sirius A and C,SIRIUS A AND B,S*r**s A *nd B\nRoss 154,9.693 LY,M3.5,-26506942,Ross 155,ROSS 154,R*ss 154\nRoss 248,10.32 LY,M5.5V,-18054910,Ross 249,ROSS 248,R*ss 248\nEpsilon Eridani,10.5 LY,K2V,931307088,Epsilon Eridanj,EPSILON ERIDANI,Eps*l*n Er*d*n*\n", @waggoner="Star", @astrolabe=false, @grub=Star, @rhumb_lines=#<File:/Users/pboling/RubymineProjects/empty_csv_pirate_app/log/csv/Star.20091004.export.3.csv (closed)>, @nocturnal="Star.20091004.export.3.csv", @aft=".csv", @gibbet=".export", @shrouds=",", @swag=[#<Star:0x2202db0 @spectral_type="M5.5Vc", @distance="4.2 LY", @name="Proxima Centauri">, #<Star:0x2202d10 @spectral_type="G2V", @distance="4.3 LY", @name="Rigil Kentaurus">, #<Star:0x2202c98 @spectral_type="M3.8V", @distance="5.9 LY", @name="Barnard's Star">, #<Star:0x2202c20 @spectral_type="M5.8Vc", @distance="7.7 LY", @name="Wolf 359">, #<Star:0x2202ba8 @spectral_type="M2V", @distance="8.26 LY", @name="Lalande 21185">, #<Star:0x2202b30 @spectral_type="M5.5 de & M6 Ve", @distance="8.73 LY", @name="Luyten 726-8A and B">, #<Star:0x2202ab8 @spectral_type="A1Vm", @distance="8.6 LY", @name="Sirius A and B">, #<Star:0x2202a40 @spectral_type="M3.5", @distance="9.693 LY", @name="Ross 154">, #<Star:0x22029c8 @spectral_type="M5.5V", @distance="10.32 LY", @name="Ross 248">, #<Star:0x2202950 @spectral_type="K2V", @distance="10.5 LY", @name="Epsilon Eridani">], @chart=["log", "csv"]>
162
+ rails development >a.weigh_anchor
163
+ name,distance,spectral_type,namehash,namenext,nameupcase,star_vowels
164
+ Proxima Centauri,4.2 LY,M5.5Vc,971295636,Proxima Centaurj,PROXIMA CENTAURI,Pr*x*m* C*nt**r*
165
+ Rigil Kentaurus,4.3 LY,G2V,-231389024,Rigil Kentaurut,RIGIL KENTAURUS,R*g*l K*nt**r*s
166
+ Barnard's Star,5.9 LY,M3.8V,1003964756,Barnard's Stas,BARNARD'S STAR,B*rn*rd's St*r
167
+ Wolf 359,7.7 LY,M5.8Vc,429493790,Wolf 360,WOLF 359,W*lf 359
168
+ Lalande 21185,8.26 LY,M2V,466625069,Lalande 21186,LALANDE 21185,L*l*nd* 21185
169
+ Luyten 726-8A and B,8.73 LY,M5.5 de & M6 Ve,-886693495,Luyten 726-8A and C,LUYTEN 726-8A AND B,L*yt*n 726-8A *nd B
170
+ Sirius A and B,8.6 LY,A1Vm,-969980943,Sirius A and C,SIRIUS A AND B,S*r**s A *nd B
171
+ Ross 154,9.693 LY,M3.5,-26506942,Ross 155,ROSS 154,R*ss 154
172
+ Ross 248,10.32 LY,M5.5V,-18054910,Ross 249,ROSS 248,R*ss 248
173
+ Epsilon Eridani,10.5 LY,K2V,931307088,Epsilon Eridanj,EPSILON ERIDANI,Eps*l*n Er*d*n*
174
+ => #<File:/Users/pboling/RubymineProjects/empty_csv_pirate_app/log/csv/Star.20091004.export.3.csv (closed)>
175
+
176
+ ## Advanced Usage & Examples
177
+
178
+ Assuming a Make (as in manufacturers of automobiles) model like this:
179
+
180
+ # ## Schema Information
181
+ #
182
+ # Table name: makes
183
+ #
184
+ # id :integer(4) not null, primary key
185
+ # name :string(255)
186
+ # factory :string(255)
187
+ # sales :integer(4)
188
+ #
189
+
190
+ class Make < ActiveRecord::Base
191
+ has_many :vehicle_models
192
+ named_scope :factory_in_germany, :conditions => ["factory = ?", "Germany"]
193
+
194
+ # Showing all available options with their default values
195
+ has_csv_pirate_ship :chart => ['log','csv'] # Array of Strings: directory where csv will be created (Yes, it creates all of them if they do not already exist)
196
+ :aft => '.csv' # String: filename extension, usually this would be '.csv', but can be whatever you want.
197
+ :gibbet => '.export' # String: Middle part of the filename {the '.' is required for iterative filenames, set :swab => :none to turn off iterative filenames}
198
+ # Comes after waggoner and chronometer, before swabbie and aft
199
+ :waggoner => "#{Make}" # String: First part of filename
200
+
201
+ # Must provide :swag or :grub (not both)
202
+ :swag => nil # Array of objects: to use to create the CSV (i.e. you've already done the query and have the results you want a CSV of)
203
+ :grub => Make # Class: on which to call the method chain in :spyglasses that will return the array of objects to be placed in :swag by CsvPirate (See description of swag above).
204
+ :spyglasses => [:all] # Array of symbols/strings: Methods that will be chained together and called on :grub in order to get the :swag records which will become the rows of the CSV.
205
+ :booty => Make.column_names # Array of symbols/strings or nested hashes of symbols/strings: Methods to call on each object in :swag. These become the columns of the CSV. The method names become the CSV column headings. Methods can be chained to dig deep (e.g. traverse several ActiveRecord associations) to get at a value for the CSV. To call instance methods that include arguments, pass a booty element of an array such as [:method_name, arg1, arg2...].
206
+
207
+ :swab => :counter # Symbol: What kind of file counter to use to avoid overwriting the CSV file, :counter is Integer, :timestamp is HHMMSS, :none is no file counter, increasing the likelihood of duplicate filenames on successive csv exports.
208
+ :mop => :clean # Symbol: If we DO end up writing to a preexisting file (by design or accident) should we overwrite (:clean) or append (:dirty)?
209
+ :shrouds => ',' # String: Delimiter for CSV. '\t' will create a tab delimited file (tsv), '|' will create a pipe delimited file.
210
+ :bury_treasure => true # Boolean: Should the array of objects in :swag be stored in the CsvPirate object for later inspection?
211
+ :blackjack => {:humanize => '-'} # Hash: Specify how you want your CSV header
212
+ # {:join => '-'} joins the method names called to get hte data for that column with '_' underscores.
213
+ # {:humanize => '-'} first joins as above, then humanizes the string (this is the default)
214
+ # {:array => ['col1',col2','col3'] Uses the column names provided in the array. If the array provided is too short defaults to :humanize =>'_'
215
+
216
+ # A customized version to create a tab delimited file for this class might look like this:
217
+ # has_csv_pirate_ship :spyglasses => [:factory_in_germany],
218
+ # :booty => [:id, :name],
219
+ # :shrouds => '\t'
220
+ # # keeping the rest of the options at the default values, so they don't need to be defined.
221
+ end
222
+
223
+ To create a csv of the names and ids of makes with factories in germany and return the text of the export:
224
+
225
+ 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 :)
226
+
227
+ The name of the csv that comes out will be (by default located in log directory):
228
+
229
+ Make.20090930.export.13.csv
230
+
231
+ 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.
232
+
233
+ All of those filename parts are customizable to a degree. For example if you want to have the date NOT be today's date you can supply your own date:
234
+
235
+ Make.walk_the_plank({:chronometer => Date.parse("December 21, 2012") })
236
+ # File name would be: Make.20121221.export.13.csv
237
+
238
+ Make.walk_the_plank({:chronometer => false })
239
+ # File name would be: Make.export.13.csv
240
+
241
+ What if you want the file name to be always the same and to always append to the end of it?
242
+
243
+ # Example: I want the file to be named "data", with no extension, both of the following accomplish that:
244
+ Make.walk_the_plank({:chronometer => false, :gibbet => "", :aft => "", :swab => :none, :waggoner => 'data'})
245
+ Make.blindfold(:chronometer => false, :gibbet => "", :aft => "", :swab => :none, :waggoner => 'data')
246
+
247
+ All of the options to has_csv_pirate_ship are available to walk_the_plank, land_ho, and blindfold, as well as to the raw class methods CsvPirate::TheCapn.new and CsvPirate::TheCapn.create, but not necessarily the other way around.
248
+
249
+ You can also customize the CSV, for example if you want to customize which columns are in the csv:
250
+
251
+ Make.walk_the_plank({:booty => [:id, :name, :sales]})
252
+
253
+ You want a timestamp file counter instead of the integer default:
254
+
255
+ Make.walk_the_plank({:booty => [:id, :name, :sales], :swab => :timestamp})
256
+
257
+ If you want to append each export to the end of the same file (on a per day basis):
258
+
259
+ Make.walk_the_plank({:booty => [:id, :name, :sales], :spyglasses => [:all], :swab => :none, :mop => :dirty})
260
+
261
+ If you want to restrict the csv to a particular set of named scopes:
262
+
263
+ Make.walk_the_plank({:booty => [:id, :name, :sales], :spyglasses => [:with_abs, :with_esc, :with_heated_seats]})
264
+
265
+ If you want to create a tsv (tab-delimited) or psv (pipe-delimited) instead of a csv:
266
+
267
+ Make.walk_the_plank({:booty => [:id, :name, :sales], :shrouds => '\t'})
268
+ Make.walk_the_plank({:booty => [:id, :name, :sales], :shrouds => '|'})
269
+
270
+ If you have a method in the Make class like this:
271
+
272
+ def to_slug
273
+ "#{self.name}_#{self.id}"
274
+ end
275
+
276
+ getting it in the CSV is easy peasy:
277
+
278
+ Make.walk_the_plank({:booty => [:id, :name, :to_slug]})
279
+
280
+ If you want to traverse Active Record Associations, or call a method on the return value of another method (unlimited nesting):
281
+
282
+ Make.walk_the_plank({:booty => [:id, :name, :to_slug, {:to_slug => :hash}]}) #will call .hash on the result of make.to_slug
283
+ Make.walk_the_plank({:booty => [:id, :name, :to_slug, {:to_slug => {:hash => :abs}}]}) #returns make.to_slug.hash.abs
284
+
285
+ If you want to build your booty using instance functions that require arguments, use an array:
286
+
287
+ Make.walk_the_plank({:booty => [:id, :name, [:value_on, Date.today]}) # will call make.value_on(Date.today)
288
+
289
+ 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.
290
+
291
+ You can also use the raw CsvPirate class itself directly wherever you want.
292
+
293
+ The following two sets of code are identical:
294
+
295
+ csv_pirate = CsvPirate::TheCapn.new({
296
+ :grub => User,
297
+ :spyglasses => [:active,:logged_in],
298
+ :waggoner => 'active_users_logged_in',
299
+ :booty => ["id","number","login","created_at"],
300
+ :chart => ['log','csv']
301
+ })
302
+ csv_pirate.hoist_mainstay() # creates CSV file and writes out the rows
303
+
304
+ CsvPirate::TheCapn.create({
305
+ :grub => User,
306
+ :spyglasses => [:active,:logged_in],
307
+ :waggoner => 'active_users_logged_in',
308
+ :booty => ["id","number","login","created_at"],
309
+ :chart => ['log','csv']
310
+ })# creates CSV file and writes out the rows
311
+
312
+ Another example using swag instead of grub:
313
+
314
+ users = User.logged_out.inactive
315
+ csv_pirate = CsvPirate::TheCapn.new({
316
+ :swag => users,
317
+ :waggoner => 'inactive_users_not_logged_in',
318
+ :booty => ["id","number","login","created_at"],
319
+ :chart => ['log','csv']
320
+ })
321
+ csv_pirate.hoist_mainstay()
322
+
323
+ Then if you want to get your hands on the loot immediately:
324
+
325
+ csv_pirate.weigh_anchor()
326
+
327
+ For those who can't help but copy/paste into console and then edit:
328
+
329
+ csv_pirate = CsvPirate::TheCapn.new({:grub => User,:spyglasses => [:active,:logged_in],:waggoner => 'active_users_logged_in',:booty => ["id","number","login","created_at"],:chart => ['log','csv']})
330
+
331
+ OR
332
+
333
+ csv_pirate = CsvPirate::TheCapn.new({:swag => users,:waggoner => 'inactive_users_not_logged_in',:booty => ["id","number","login","created_at"],:chart => ['log','csv']})
334
+
335
+
336
+ ## Downloading the CSV
337
+
338
+ You have the same Make class as above, and you have a MakeController:
339
+
340
+ class MakeController < ApplicationController
341
+ def download_csv
342
+ csv_pirate = Make.blindfold
343
+
344
+ # maroon saves the read to the file system, by using the text of the csv stored in the CsvPirate object.
345
+ send_data csv_pirate.maroon, ...
346
+ :type => 'text/csv; charset=iso-8859-1; header=present',
347
+ :disposition => "attachment; filename=#{csv_pirate.nocturnal}"
348
+
349
+ # However if CSVs are created using multiple CsvPirate objects that all append to a single file,
350
+ # we need to read the final product from the fs.
351
+ #send_file csv_pirate.brigantine,
352
+ # :type => 'text/csv; charset=utf-8; header=present',
353
+ # :disposition => "attachment; filename=#{csv_pirate.nocturnal}"
354
+ end
355
+ end
356
+
357
+ ## Advanced Example with Nested Methods
358
+
359
+ You have a VehicleModel class and the same Make class as up above:
360
+
361
+ # ## Schema Information
362
+ #
363
+ # Table name: vehicle_models
364
+ #
365
+ # id :integer(4) not null, primary key
366
+ # name :string(255)
367
+ # year :integer(4)
368
+ # horsepower :integer(4)
369
+ # price :integer(4)
370
+ # electric :boolean(1)
371
+ # make_id :integer(4)
372
+ #
373
+
374
+ class VehicleModel < ActiveRecord::Base
375
+ belongs_to :make
376
+ has_csv_pirate_ship :booty => [:id, :name, :year,
377
+ {:make => :name},
378
+ {:tires => {:size => {:width => :inches}}}]
379
+ def tires; TireSize.new; end
380
+ end
381
+
382
+ class TireSize
383
+ # To call an instance method you need to return an instance
384
+ def size; TireWidth.new; end
385
+ end
386
+
387
+ class TireWidth
388
+ # To call a class method you need to return the class object
389
+ def width; Measurement; end
390
+ end
391
+
392
+ class Measurement
393
+ def self.inches; 13; end
394
+ end
395
+
396
+ Then to create the CSV:
397
+
398
+ a = VehicleModel.blindfold
399
+
400
+ Then check the output from the console:
401
+
402
+ a.weigh_anchor
403
+
404
+ Id,Name,Year,Make name,Tires size width inches
405
+ 1,Cavalier,1999,Chevrolet,13
406
+ 2,Trailblazer,2006,Chevrolet,13
407
+ 3,Corvette,2010,Chevrolet,13
408
+ 4,Mustang,1976,Ford,13
409
+ 5,Lebaron,1987,Chrysler,13
410
+ 6,Avalon,1996,Toyota,13
411
+ => #<File:/Users/pboling/RubymineProjects/empty_csv_pirate_app/log/VehicleModel.20091001.export.2.csv (closed)>
412
+
413
+ Joy to recursive code everywhere!
414
+
415
+ If you wanted to create the CsvPirate object and then modify it before creating the csv you can do that too.
416
+ Does not actually create the csv, so you need to do this in your code:
417
+
418
+ csv_pirate = VehicleModel.land_ho({:booty => [:id, :name, :year, :horsepower, :price]})
419
+
420
+ This allows you to modify the csv_pirate object before creating the csv like this:
421
+
422
+ csv_pirate.booty -= [:id, :name]
423
+ csv_pirate.hoist_mainstay()
424
+
425
+ ## Tests
426
+
427
+ The tests are run with rspec. The test suite is expanding. Currently there is ample coverage of basic functionality.
428
+
429
+ If on a Ruby prior to Ruby 1.9 you will also need the fastercsv gem
430
+
431
+ To run tests cd to where ever you have csv_pirate installed, and do:
432
+
433
+ bundle exec rake spec
434
+
435
+
436
+ ## How you can help!
437
+
438
+ This code was written in 2008, as one of my first gems, and is aging well, but can certainly be improved.
439
+
440
+ Take a look at the `reek` list, which is the file called `REEK`, and stat fixing things. Once you complete a change, run the tests. See "Running the gem tests".
441
+
442
+ If the tests pass refresh the `reek` list:
443
+
444
+ bundle exec rake reek > REEK
445
+
446
+ Follow the instructions for "Contributing" below.
447
+
448
+
449
+ ## Compatibility with Micrsoft Excel
450
+
451
+ Microsoft Office (Excel) "SYLK Invalid Format" Error will occur if the string "ID" (without quotes)
452
+ is at the beginning of the CSV file. This is strangely inconvenient for rails CSVs since every table
453
+ in rails starts with an id column. So buyer beware... make your first column lower case 'id'
454
+ if you need to export the id field.
455
+
456
+ http://www.bradino.com/misc/sylk-file-format-is-not-valid/
457
+
458
+
459
+ ## Contributing to CsvPirate
460
+
461
+ * Check out the latest master to make sure the feature hasn't been implemented or the bug hasn't been fixed yet
462
+ * Check out the issue tracker to make sure someone already hasn't requested it and/or contributed it
463
+ * Fork the project
464
+ * Start a feature/bugfix branch
465
+ * Commit and push until you are happy with your contribution
466
+ * Make sure to add tests, rspec preferred, for it. This is important so I don't break it in a future version unintentionally.
467
+ * Please try not to mess with the Rakefile, version, or change log. If you want to have your own version, or is otherwise necessary, that is fine, but please isolate to its own commit so I can cherry-pick around it.
468
+
469
+ ## On The Web
470
+
471
+ Release Announcement:
472
+ http://galtzo.blogspot.com/2009/03/csv-pirate.html
473
+
474
+ ## Versioning
475
+
476
+ This library aims to adhere to [Semantic Versioning 2.0.0][semver].
477
+ Violations of this scheme should be reported as bugs. Specifically,
478
+ if a minor or patch version is released that breaks backward
479
+ compatibility, a new version should be immediately released that
480
+ restores compatibility. Breaking changes to the public API will
481
+ only be introduced with new major versions.
482
+
483
+ As a result of this policy, you can (and should) specify a
484
+ dependency on this gem using the [Pessimistic Version Constraint][pvc] with two digits of precision.
485
+
486
+ For example:
487
+
488
+ spec.add_dependency 'csv_pirate', '~> 5.0'
489
+
490
+ ## Thanks
491
+
492
+ Thanks go to:
493
+
494
+ * [Peter Boling][railsbling], author of CsvPirate, runs the joint.
495
+ * TimePerks LLC (http://www.timeperks.com) - Many useful enhancements were requested and paid for by TimePerks
496
+
497
+ ----------------------------------------------------------------------------------
498
+ Author: Peter Boling, peter.boling at gmail dot com
499
+
500
+ Copyright (c) 2008-2013 [Peter H. Boling][peterboling] of [RailsBling.com][railsbling], released under the MIT license. See LICENSE for details.
501
+
502
+ [semver]: http://semver.org/
503
+ [pvc]: http://docs.rubygems.org/read/chapter/16#page74
504
+ [railsbling]: http://www.railsbling.com
505
+ [peterboling]: http://www.peterboling.com
506
+ [documentation]: http://rdoc.info/github/pboling/flag_shih_tzu/frames
507
+ [homepage]: https://github.com/pboling/flag_shih_tzu