to-csv 1.0.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/CHANGELOG.rdoc CHANGED
@@ -1,3 +1,9 @@
1
- == 1.0.0
2
-
3
- * First release
1
+ == 1.0.1 2009-12-24
2
+
3
+ * Now compatible with Ruby 1.9.1
4
+ * Updated documentation to reflect Ruby 1.9.1 support
5
+
6
+ == 1.0.0 2009-12-23
7
+
8
+ * First release
9
+
data/MIT-LICENSE CHANGED
@@ -1,20 +1,20 @@
1
- Copyright (c) 2009 Ícaro Leopoldino da Motta
2
-
3
- Permission is hereby granted, free of charge, to any person obtaining
4
- a copy of this software and associated documentation files (the
5
- "Software"), to deal in the Software without restriction, including
6
- without limitation the rights to use, copy, modify, merge, publish,
7
- distribute, sublicense, and/or sell copies of the Software, and to
8
- permit persons to whom the Software is furnished to do so, subject to
9
- the following conditions:
10
-
11
- The above copyright notice and this permission notice shall be
12
- included in all copies or substantial portions of the Software.
13
-
14
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
- LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
- OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
- WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
1
+ Copyright (c) 2009 Ícaro Leopoldino da Motta
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.rdoc CHANGED
@@ -1,188 +1,191 @@
1
- = ToCSV
2
-
3
-
4
- ToCSV is a gem for converting arrays to CSV by calling +to_csv+.
5
- These arrays can contain different data structures, as long as they are homogeneous, like the ones
6
- described below:
7
-
8
- * A simple array of anything that responds to <tt>to_s</tt>: <tt>['Date', Time.now].to_csv</tt>
9
- * An array of hashes: <tt>[ {'Name' => 'Icaro', 'Age' => 23}, {'Name' => 'Gabriel', 'Age' => 16} ].to_csv</tt>
10
- * A matrix: <tt>[['Name', 'Age'], ['Icaro', 23], ['Gabriel', 16]].to_csv</tt>
11
- * A hash like array: <tt>[ [['Name', 'Icaro'], ['Age', 23]], [['Name', 'Gabriel'], ['Age', 16]] ].to_csv</tt>
12
- * An array of ActiveRecord objects: <tt>@users.to_csv(:except => [:password, :phone], :timestamps => true)</tt>
13
-
14
-
15
- === Requirements
16
-
17
- You must have FasterCSV installed:
18
- $ sudo gem install fastercsv
19
-
20
- And also ActiveSupport:
21
- $ sudo gem install active_support
22
-
23
- ToCSV has been tested with Ruby 1.8.6/1.8.7.
24
-
25
-
26
- === Configuration
27
-
28
- If you want to use this gem with Rails, put the following requirement in your environment.rb:
29
-
30
- config.gem 'to-csv', :lib => 'to_csv', :source => 'http://gemcutter.org'
31
-
32
- After that, if you need to globally configure the gem, just create a <i>to_csv.rb</i> file in <i>initializers</i>.
33
-
34
- ToCSV.byte_order_marker = true
35
- ToCSV.timestamps = true
36
- ToCSV.locale = 'en-US'
37
- ToCSV.primary_key = false
38
- ToCSV.csv_options = { :col_sep => ',', :row_sep => "\r\n" }
39
-
40
-
41
- == Examples
42
-
43
- Let's start with the most simple example.
44
-
45
- ['Alfred Hitchcock', 'Robert Mitchum', 'Lucille Ball'].to_csv
46
- #=> "Alfred Hitchcock;Robert Mitchum;Lucille Ball\n"
47
-
48
-
49
- Or, if we have an array of arrays (i.e. a matrix) we can create tabular data.
50
- [
51
- ['Name', 'Gender'],
52
- ['Alfred', 'M'],
53
- ['Robert', 'M'],
54
- ['Lucille', 'F']
55
- ].to_csv #=> "Name;Gender\nAlfred;M\nRobert;M\nLucille;F\n"
56
-
57
-
58
- Almost always, when we generate CSV files, we want it to have appropriate
59
- headers, so a better approach might be to use an array of hashes.
60
-
61
- [
62
- { 'Name' => 'Alfred', 'Gender' => 'M' },
63
- { 'Name' => 'Robert', 'Gender' => 'M' },
64
- { 'Name' => 'Lucille', 'Gender' => 'F' }
65
- ].to_csv #=> "Gender;Name\nM;Alfred\nM;Robert\nF;Lucille\n"
66
-
67
-
68
- Look carefully to the above output. You can see that when we use hashes we can
69
- no longer be sure of the headers' order. When we are working with tabular data
70
- the headers' order can be very important, thus we can use a somewhat similar
71
- data structure:
72
-
73
- [
74
- [ ['Name', 'Alfred'], ['Gender', 'M'] ],
75
- [ ['Name', 'Robert'], ['Gender', 'M'] ],
76
- [ ['Name', 'Lucille'], ['Gender', 'F'] ]
77
- ].to_csv #=> "Name;Gender\nAlfred;M\nRobert;M\nLucille;F\n"
78
-
79
- That's a lot to type... The first example was much simpler...
80
-
81
- There is the <tt>headers</tt> option. You can use it in all the examples above
82
- to enable/disable headers from the output. Default is to show (true).
83
-
84
- users = [{ 'Name' => 'Alfred', 'Gender' => 'M' }]
85
- users.to_csv(:headers => false)
86
-
87
-
88
- ==== Active Record Objects
89
-
90
- When we're building our data like the previous examples we have very few options
91
- compared to what can be passed when converting an array of AR objects. Again,
92
- the easiest way:
93
-
94
- # Anywhere in your app.
95
- # By default, all available model attributes (DB columns) are going to be used
96
- # except timestamps and the primary key of the record
97
- @users = User.all
98
- File.open('path/to/file.csv', 'w') { |io| io.puts @users.to_csv }
99
-
100
-
101
- ==== Headers
102
-
103
- You can control the order and the text of any header. You can accomplish that
104
- in various ways.
105
-
106
- By default all attribute/method names will be sorted in alphabetical order. So
107
- imagine a person model have +name+, +age+ and +email+ as attributes, and you
108
- want to get the following output:
109
-
110
- Name | E-mail | Age
111
- ... | ... | ..
112
- ... | ... | ..
113
-
114
- You can tell <i>to-csv</i> to use a specific locale. If you don't, it uses
115
- your app current locale. It will try to translate attributes to a
116
- more friendly text by using the scope <tt>[:activerecord, :attributes, <model name>]</tt>.
117
- If the translation doesn't exist the header's text is going to be humanized.
118
-
119
- The order of columns can be changed with the option +headers+. The way this
120
- option works is very similar to the <tt>plugins</tt> method in your Rails
121
- <i>environment.rb</i> file.
122
-
123
- * If you pass +nil+ (default) then headers/columns will be in alphabetical order.
124
- * If you pass an empty array or +false+, no headers will be shown.
125
- * Instead, if you pass a non empty array, headers will be sorted in the order specified. <tt>:all</tt> can be used as a placeholder for all attributes not explicitly named.
126
-
127
- So, in our example above, we can say:
128
-
129
- @users.to_csv(:headers => [:name, :email, :age])
130
-
131
- Or, using the placeholder +all+, which is not very useful here:
132
-
133
- @users.to_csv(:headers => [:name, :email, :all])
134
-
135
- If you want a completely different result you could, for instance, map all
136
- users to a hash. Example:
137
-
138
- # This makes use of a hash to completely change the CSV output.
139
- @users.map do |user|
140
- {
141
- 'Name' => user.name,
142
- 'Age' => user.age,
143
- 'Total Comments' => user.comments.count
144
- }
145
- end.to_csv
146
-
147
-
148
- ===== Passing a Block
149
-
150
- Sometimes you may want to change just one value out of six for example. The best
151
- way to go is to pass a block so that you don't have to repeat yourself writing
152
- five headers and it's obvious values and also loosing I18n translations.
153
-
154
- # The block yields a new OpenStruct for each object in the list. By calling
155
- # methods on this struct you can change their default values.
156
- @users.to_csv do |csv, user|
157
- csv.date_of_birth = user.date_of_birth.to_s(:long)
158
- end
159
-
160
-
161
- ===== A More Complete Example
162
-
163
- # index.html.haml
164
- = link_to 'export (CSV)', users_url(:csv)
165
-
166
- # index action in users controller
167
- def index
168
- @users = User.all
169
- respond_to do |format|
170
- format.html
171
- format.csv { send_data @users.to_csv, :filename => 'users_report.csv' }
172
- end
173
- end
174
-
175
-
176
- ==== Full Customization
177
-
178
- You can always customize the output if you wish by building arrays of hashes,
179
- arrays of arrays of bidimensional arrays etc :). Or you can obviously mix
180
- anything you want and even use FasterCSV directly.
181
-
182
- @user.to_csv { :only => [:name, :email] }, :col_sep => ','
183
-
184
- There are other options for you to customize the output. Take a look at the
185
- <tt>to_csv</tt> method documentation.
186
-
187
- Copyright (c) 2009 Ícaro Leopoldino da Motta, released under the MIT license.
188
-
1
+ = ToCSV
2
+
3
+
4
+ ToCSV is a gem for converting arrays to CSV by calling +to_csv+.
5
+ These arrays can contain different data structures, as long as they are homogeneous, like the ones
6
+ described below:
7
+
8
+ * A simple array of anything that responds to <tt>to_s</tt>: <tt>['Date', Time.now].to_csv</tt>
9
+ * An array of hashes: <tt>[ {'Name' => 'Icaro', 'Age' => 23}, {'Name' => 'Gabriel', 'Age' => 16} ].to_csv</tt>
10
+ * A matrix: <tt>[['Name', 'Age'], ['Icaro', 23], ['Gabriel', 16]].to_csv</tt>
11
+ * A hash like array: <tt>[ [['Name', 'Icaro'], ['Age', 23]], [['Name', 'Gabriel'], ['Age', 16]] ].to_csv</tt>
12
+ * An array of ActiveRecord objects: <tt>@users.to_csv(:except => [:password, :phone], :timestamps => true)</tt>
13
+
14
+
15
+ === Requirements
16
+
17
+ ToCSV has been tested with Ruby 1.8.6/1.8.7/1.9.1.
18
+
19
+ If you are using Ruby 1.9 the only dependency to use the basic features is +ActiveSupport+.
20
+ Otherwise you will need +fastercsv+. You will receive a warning if you don't meet the requirements.
21
+
22
+ # If you don't have Rails installed...
23
+ $ sudo gem install activesupport
24
+
25
+ # And if your Ruby version is lower than 1.9
26
+ $ sudo gem install fastercsv
27
+
28
+
29
+ === Configuration
30
+
31
+ If you want to use this gem with Rails, put the following requirement in your environment.rb:
32
+
33
+ config.gem 'to-csv', :lib => 'to_csv', :source => 'http://gemcutter.org'
34
+
35
+ After that, if you need to globally configure the gem, just create a <i>to_csv.rb</i> file in <i>initializers</i>.
36
+
37
+ ToCSV.byte_order_marker = true
38
+ ToCSV.timestamps = true
39
+ ToCSV.locale = 'en-US'
40
+ ToCSV.primary_key = false
41
+ ToCSV.csv_options = { :col_sep => ',', :row_sep => "\r\n" }
42
+
43
+
44
+ == Examples
45
+
46
+ Let's start with the most simple example.
47
+
48
+ ['Alfred Hitchcock', 'Robert Mitchum', 'Lucille Ball'].to_csv
49
+ #=> "Alfred Hitchcock;Robert Mitchum;Lucille Ball\n"
50
+
51
+
52
+ Or, if we have an array of arrays (i.e. a matrix) we can create tabular data.
53
+ [
54
+ ['Name', 'Gender'],
55
+ ['Alfred', 'M'],
56
+ ['Robert', 'M'],
57
+ ['Lucille', 'F']
58
+ ].to_csv #=> "Name;Gender\nAlfred;M\nRobert;M\nLucille;F\n"
59
+
60
+
61
+ Almost always, when we generate CSV files, we want it to have appropriate
62
+ headers, so a better approach might be to use an array of hashes.
63
+
64
+ [
65
+ { 'Name' => 'Alfred', 'Gender' => 'M' },
66
+ { 'Name' => 'Robert', 'Gender' => 'M' },
67
+ { 'Name' => 'Lucille', 'Gender' => 'F' }
68
+ ].to_csv #=> "Gender;Name\nM;Alfred\nM;Robert\nF;Lucille\n"
69
+
70
+
71
+ Look carefully to the above output. You can see that when we use hashes we can
72
+ no longer be sure of the headers' order (true for Ruby versions older than 1.9).
73
+ When we are working with tabular data the headers' order can be very important,
74
+ thus we can use a somewhat similar data structure:
75
+
76
+ [
77
+ [ ['Name', 'Alfred'], ['Gender', 'M'] ],
78
+ [ ['Name', 'Robert'], ['Gender', 'M'] ],
79
+ [ ['Name', 'Lucille'], ['Gender', 'F'] ]
80
+ ].to_csv #=> "Name;Gender\nAlfred;M\nRobert;M\nLucille;F\n"
81
+
82
+ That's a lot to type... The first example was much simpler...
83
+
84
+ There is the <tt>headers</tt> option. You can use it in all the examples above
85
+ to enable/disable headers from the output. Default is to show (true).
86
+
87
+ users = [{ 'Name' => 'Alfred', 'Gender' => 'M' }]
88
+ users.to_csv(:headers => false)
89
+
90
+
91
+ ==== Active Record Objects
92
+
93
+ When we're building our data like the previous examples we have very few options
94
+ compared to what can be passed when converting an array of AR objects. Again,
95
+ the easiest way:
96
+
97
+ # Anywhere in your app.
98
+ # By default, all available model attributes (DB columns) are going to be used
99
+ # except timestamps and the primary key of the record
100
+ @users = User.all
101
+ File.open('path/to/file.csv', 'w') { |io| io.puts @users.to_csv }
102
+
103
+
104
+ ==== Headers
105
+
106
+ You can control the order and the text of any header. You can accomplish that
107
+ in various ways.
108
+
109
+ By default all attribute/method names will be sorted in alphabetical order. So
110
+ imagine a person model have +name+, +age+ and +email+ as attributes, and you
111
+ want to get the following output:
112
+
113
+ Name | E-mail | Age
114
+ ... | ... | ..
115
+ ... | ... | ..
116
+
117
+ You can tell <i>to-csv</i> to use a specific locale. If you don't, it uses
118
+ your app current locale. It will try to translate attributes to a
119
+ more friendly text by using the scope <tt>[:activerecord, :attributes, <model name>]</tt>.
120
+ If the translation doesn't exist the header's text is going to be humanized.
121
+
122
+ The order of columns can be changed with the option +headers+. The way this
123
+ option works is very similar to the <tt>plugins</tt> method in your Rails
124
+ <i>environment.rb</i> file.
125
+
126
+ * If you pass +nil+ (default) then headers/columns will be in alphabetical order.
127
+ * If you pass an empty array or +false+, no headers will be shown.
128
+ * Instead, if you pass a non empty array, headers will be sorted in the order specified. <tt>:all</tt> can be used as a placeholder for all attributes not explicitly named.
129
+
130
+ So, in our example above, we can say:
131
+
132
+ @users.to_csv(:headers => [:name, :email, :age])
133
+
134
+ Or, using the placeholder +all+, which is not very useful here:
135
+
136
+ @users.to_csv(:headers => [:name, :email, :all])
137
+
138
+ If you want a completely different result you could, for instance, map all
139
+ users to a hash. Example:
140
+
141
+ # This makes use of a hash to completely change the CSV output.
142
+ @users.map do |user|
143
+ {
144
+ 'Name' => user.name,
145
+ 'Age' => user.age,
146
+ 'Total Comments' => user.comments.count
147
+ }
148
+ end.to_csv
149
+
150
+
151
+ ===== Passing a Block
152
+
153
+ Sometimes you may want to change just one value out of six for example. The best
154
+ way to go is to pass a block so that you don't have to repeat yourself writing
155
+ five headers and it's obvious values and also loosing I18n translations.
156
+
157
+ # The block yields a new OpenStruct for each object in the list. By calling
158
+ # methods on this struct you can change their default values.
159
+ @users.to_csv do |csv, user|
160
+ csv.date_of_birth = user.date_of_birth.to_s(:long)
161
+ end
162
+
163
+
164
+ ===== A More Complete Example
165
+
166
+ # index.html.haml
167
+ = link_to 'export (CSV)', users_url(:csv)
168
+
169
+ # index action in users controller
170
+ def index
171
+ @users = User.all
172
+ respond_to do |format|
173
+ format.html
174
+ format.csv { send_data @users.to_csv, :filename => 'users_report.csv' }
175
+ end
176
+ end
177
+
178
+
179
+ ==== Full Customization
180
+
181
+ You can always customize the output if you wish by building arrays of hashes,
182
+ arrays of arrays of bidimensional arrays etc :). Or you can obviously mix
183
+ anything you want and even use FasterCSV directly.
184
+
185
+ @user.to_csv { :only => [:name, :email] }, :col_sep => ','
186
+
187
+ There are other options for you to customize the output. Take a look at the
188
+ <tt>to_csv</tt> method documentation.
189
+
190
+ Copyright (c) 2009 Ícaro Leopoldino da Motta, released under the MIT license.
191
+
data/Rakefile CHANGED
@@ -1,36 +1,52 @@
1
- #encoding: utf-8
2
- require 'rubygems'
3
- require 'rake'
4
- require 'rake/clean'
5
- require 'rake/gempackagetask'
6
- load 'test/tasks.rake'
7
-
8
- TO_CSV_VERSION = '1.0.0'
9
- CLEAN.include('pkg')
10
-
11
- spec = Gem::Specification.new do |s|
12
- s.author = "Ícaro Leopoldino da Motta"
13
- s.email = "icaro.ldm@gmail.com"
14
- s.platform = Gem::Platform::RUBY
15
- s.name = "to-csv"
16
- s.summary = s.description = "Convert arrays to CSV (array of hashes, matrixes, ActiveRecord objects etc)."
17
- s.homepage = "http://github.com/ilmotta/to-csv"
18
- s.version = TO_CSV_VERSION
19
-
20
- s.add_dependency 'fastercsv', '>= 1.5.0'
21
- s.add_dependency 'activesupport', '>= 2.3.5'
22
-
23
- s.has_rdoc = true
24
- s.require_path = "lib"
25
- s.extra_rdoc_files = FileList['*.rdoc']
26
- s.files = FileList['init.rb', 'MIT-LICENSE', 'Rakefile', 'lib/**/*', 'test/**/*']
27
- end
28
-
29
- Rake::GemPackageTask.new(spec) do |pkg|
30
- pkg.define
31
- end
32
-
33
- task :build => [:clean, :repackage]
34
-
35
- task :default => :test
36
-
1
+ #encoding: utf-8
2
+
3
+ require 'rubygems'
4
+ require 'rake'
5
+ require 'rake/clean'
6
+ require 'rake/gempackagetask'
7
+ load 'test/tasks.rake'
8
+
9
+ TO_CSV_VERSION = '1.0.1'
10
+ CLEAN.include('pkg')
11
+
12
+ spec = Gem::Specification.new do |s|
13
+ s.author = "Ícaro Leopoldino da Motta"
14
+ s.email = "icaro.ldm@gmail.com"
15
+ s.platform = Gem::Platform::RUBY
16
+ s.required_ruby_version = '>= 1.8.6'
17
+ s.name = "to-csv"
18
+ s.summary = s.description = "Convert arrays to CSV (array of hashes, matrixes, ActiveRecord objects etc)."
19
+ s.homepage = "http://github.com/ilmotta/to-csv"
20
+ s.version = TO_CSV_VERSION
21
+
22
+ s.add_dependency 'activesupport', '>= 2.3.5'
23
+ s.add_development_dependency 'activerecord', '>= 2.3.5'
24
+ s.add_development_dependency 'sqlite3-ruby', '>= 1.2.5'
25
+
26
+ s.has_rdoc = true
27
+ s.require_path = "lib"
28
+ s.extra_rdoc_files = FileList['*.rdoc']
29
+ s.files = FileList['init.rb', 'MIT-LICENSE', 'Rakefile', 'lib/**/*', 'test/**/*']
30
+
31
+ s.post_install_message = %q{
32
+ ========================================================================
33
+
34
+ Thanks for installing ToCSV.
35
+
36
+ If your Ruby version is lower than 1.9 you need to install fastercsv.
37
+
38
+ $ sudo gem install fastercsv
39
+
40
+ ========================================================================
41
+
42
+ }
43
+ end
44
+
45
+ Rake::GemPackageTask.new(spec) do |pkg|
46
+ pkg.define
47
+ end
48
+
49
+ task :build => [:clean, :repackage]
50
+
51
+ task :default => :test
52
+