smarter_csv 1.1.5 → 1.12.1
Sign up to get free protection for your applications and to get access to all the features.
- checksums.yaml +5 -5
- data/.rspec +1 -2
- data/.rubocop.yml +154 -0
- data/CHANGELOG.md +364 -0
- data/CONTRIBUTORS.md +56 -0
- data/Gemfile +7 -2
- data/LICENSE.txt +21 -0
- data/README.md +44 -441
- data/Rakefile +39 -19
- data/TO_DO_v2.md +14 -0
- data/docs/_introduction.md +56 -0
- data/docs/basic_api.md +157 -0
- data/docs/batch_processing.md +68 -0
- data/docs/data_transformations.md +50 -0
- data/docs/examples.md +75 -0
- data/docs/header_transformations.md +113 -0
- data/docs/header_validations.md +36 -0
- data/docs/options.md +98 -0
- data/docs/row_col_sep.md +104 -0
- data/docs/value_converters.md +68 -0
- data/ext/smarter_csv/extconf.rb +14 -0
- data/ext/smarter_csv/smarter_csv.c +97 -0
- data/lib/smarter_csv/auto_detection.rb +78 -0
- data/lib/smarter_csv/errors.rb +16 -0
- data/lib/smarter_csv/file_io.rb +50 -0
- data/lib/smarter_csv/hash_transformations.rb +91 -0
- data/lib/smarter_csv/header_transformations.rb +63 -0
- data/lib/smarter_csv/header_validations.rb +34 -0
- data/lib/smarter_csv/headers.rb +68 -0
- data/lib/smarter_csv/options.rb +95 -0
- data/lib/smarter_csv/parser.rb +90 -0
- data/lib/smarter_csv/reader.rb +243 -0
- data/lib/smarter_csv/version.rb +3 -1
- data/lib/smarter_csv/writer.rb +116 -0
- data/lib/smarter_csv.rb +91 -3
- data/smarter_csv.gemspec +43 -20
- metadata +122 -137
- data/.gitignore +0 -8
- data/.travis.yml +0 -19
- data/lib/extensions/hash.rb +0 -7
- data/lib/smarter_csv/smarter_csv.rb +0 -281
- data/spec/fixtures/basic.csv +0 -8
- data/spec/fixtures/binary.csv +0 -1
- data/spec/fixtures/carriage_returns_n.csv +0 -18
- data/spec/fixtures/carriage_returns_quoted.csv +0 -3
- data/spec/fixtures/carriage_returns_r.csv +0 -1
- data/spec/fixtures/carriage_returns_rn.csv +0 -18
- data/spec/fixtures/chunk_cornercase.csv +0 -10
- data/spec/fixtures/empty.csv +0 -5
- data/spec/fixtures/line_endings_n.csv +0 -4
- data/spec/fixtures/line_endings_r.csv +0 -1
- data/spec/fixtures/line_endings_rn.csv +0 -4
- data/spec/fixtures/lots_of_columns.csv +0 -2
- data/spec/fixtures/malformed.csv +0 -3
- data/spec/fixtures/malformed_header.csv +0 -3
- data/spec/fixtures/money.csv +0 -3
- data/spec/fixtures/no_header.csv +0 -7
- data/spec/fixtures/numeric.csv +0 -5
- data/spec/fixtures/pets.csv +0 -5
- data/spec/fixtures/quoted.csv +0 -5
- data/spec/fixtures/separator.csv +0 -4
- data/spec/fixtures/skip_lines.csv +0 -8
- data/spec/fixtures/valid_unicode.csv +0 -5
- data/spec/fixtures/with_dashes.csv +0 -8
- data/spec/fixtures/with_dates.csv +0 -4
- data/spec/smarter_csv/binary_file2_spec.rb +0 -24
- data/spec/smarter_csv/binary_file_spec.rb +0 -22
- data/spec/smarter_csv/carriage_return_spec.rb +0 -170
- data/spec/smarter_csv/chunked_reading_spec.rb +0 -14
- data/spec/smarter_csv/close_file_spec.rb +0 -15
- data/spec/smarter_csv/column_separator_spec.rb +0 -11
- data/spec/smarter_csv/convert_values_to_numeric_spec.rb +0 -48
- data/spec/smarter_csv/extenstions_spec.rb +0 -17
- data/spec/smarter_csv/header_transformation_spec.rb +0 -21
- data/spec/smarter_csv/keep_headers_spec.rb +0 -24
- data/spec/smarter_csv/key_mapping_spec.rb +0 -25
- data/spec/smarter_csv/line_ending_spec.rb +0 -43
- data/spec/smarter_csv/load_basic_spec.rb +0 -20
- data/spec/smarter_csv/malformed_spec.rb +0 -21
- data/spec/smarter_csv/no_header_spec.rb +0 -24
- data/spec/smarter_csv/not_downcase_header_spec.rb +0 -24
- data/spec/smarter_csv/quoted_spec.rb +0 -23
- data/spec/smarter_csv/remove_empty_values_spec.rb +0 -13
- data/spec/smarter_csv/remove_keys_from_hashes_spec.rb +0 -25
- data/spec/smarter_csv/remove_not_mapped_keys_spec.rb +0 -35
- data/spec/smarter_csv/remove_values_matching_spec.rb +0 -26
- data/spec/smarter_csv/remove_zero_values_spec.rb +0 -25
- data/spec/smarter_csv/skip_lines_spec.rb +0 -29
- data/spec/smarter_csv/strings_as_keys_spec.rb +0 -24
- data/spec/smarter_csv/strip_chars_from_headers_spec.rb +0 -24
- data/spec/smarter_csv/valid_unicode_spec.rb +0 -94
- data/spec/smarter_csv/value_converters_spec.rb +0 -52
- data/spec/spec/spec_helper.rb +0 -17
- data/spec/spec.opts +0 -2
- data/spec/spec_helper.rb +0 -21
data/docs/basic_api.md
ADDED
@@ -0,0 +1,157 @@
|
|
1
|
+
|
2
|
+
### Contents
|
3
|
+
|
4
|
+
* [Introduction](./_introduction.md)
|
5
|
+
* [**The Basic API**](./basic_api.md)
|
6
|
+
* [Batch Processing](././batch_processing.md)
|
7
|
+
* [Configuration Options](./options.md)
|
8
|
+
* [Row and Column Separators](./row_col_sep.md)
|
9
|
+
* [Header Transformations](./header_transformations.md)
|
10
|
+
* [Header Validations](./header_validations.md)
|
11
|
+
* [Data Transformations](./data_transformations.md)
|
12
|
+
* [Value Converters](./value_converters.md)
|
13
|
+
|
14
|
+
--------------
|
15
|
+
|
16
|
+
# SmarterCSV Basic API
|
17
|
+
|
18
|
+
Let's explore the basic APIs for reading and writing CSV files. There is a simplified API (backwards conpatible with previous SmarterCSV versions) and the full API, which allows you to access the internal state of the reader or writer instance after processing.
|
19
|
+
|
20
|
+
## Reading CSV
|
21
|
+
|
22
|
+
SmarterCSV has convenient defaults for automatically detecting row and column separators based on the given data. This provides more robust parsing of input files when you have no control over the data, e.g. when users upload CSV files.
|
23
|
+
Learn more about this [in this section](docs/examples/row_col_sep.md).
|
24
|
+
|
25
|
+
### Simplified Interface
|
26
|
+
|
27
|
+
The simplified call to read CSV files is:
|
28
|
+
|
29
|
+
```
|
30
|
+
array_of_hashes = SmarterCSV.process(file_or_input, options, &block)
|
31
|
+
|
32
|
+
```
|
33
|
+
It can also be used with a block:
|
34
|
+
|
35
|
+
```
|
36
|
+
SmarterCSV.process(file_or_input, options, &block) do |hash|
|
37
|
+
# process one row of CSV
|
38
|
+
end
|
39
|
+
```
|
40
|
+
|
41
|
+
It can also be used for processing batches of rows:
|
42
|
+
|
43
|
+
```
|
44
|
+
SmarterCSV.process(file_or_input, {chunk_size: 100}, &block) do |array_of_hashes|
|
45
|
+
# process one chunk of up to 100 rows of CSV data
|
46
|
+
end
|
47
|
+
```
|
48
|
+
|
49
|
+
### Full Interface
|
50
|
+
|
51
|
+
The simplified API works in most cases, but if you need access to the internal state and detailed results of the CSV-parsing, you should use this form:
|
52
|
+
|
53
|
+
```
|
54
|
+
reader = SmarterCSV::Reader.new(file_or_input, options)
|
55
|
+
data = reader.process
|
56
|
+
|
57
|
+
puts reader.raw_headers
|
58
|
+
```
|
59
|
+
It cal also be used with a block:
|
60
|
+
|
61
|
+
```
|
62
|
+
reader = SmarterCSV::Reader.new(file_or_input, options)
|
63
|
+
data = reader.process do
|
64
|
+
# do something here
|
65
|
+
end
|
66
|
+
|
67
|
+
puts reader.raw_headers
|
68
|
+
```
|
69
|
+
|
70
|
+
This allows you access to the internal state of the `reader` instance after processing.
|
71
|
+
|
72
|
+
|
73
|
+
## Interface for Writing CSV
|
74
|
+
|
75
|
+
To generate a CSV file, we use the `<<` operator to append new data to the file.
|
76
|
+
|
77
|
+
The input operator for adding data to a CSV file `<<` can handle single hashes, array-of-hashes, or array-of-arrays-of-hashes, and can be called one or multiple times for each file.
|
78
|
+
|
79
|
+
One smart feature of writing CSV data is the discovery of headers.
|
80
|
+
|
81
|
+
If you have hashes of data, where each hash can have different keys, the `SmarterCSV::Reader` automatically discovers the superset of keys as the headers of the CSV file. This can be disabled by either providing one of the options `headers`, `map_headers`, or `discover_headers: false`.
|
82
|
+
|
83
|
+
|
84
|
+
### Simplified Interface
|
85
|
+
|
86
|
+
The simplified interface takes a block:
|
87
|
+
|
88
|
+
```
|
89
|
+
SmarterCSV.generate(filename, options) do |csv_writer|
|
90
|
+
|
91
|
+
MyModel.find_in_batches(batch_size: 100) do |batch|
|
92
|
+
batch.pluck(:name, :description, :instructor).each do |record|
|
93
|
+
csv_writer << record
|
94
|
+
end
|
95
|
+
end
|
96
|
+
|
97
|
+
end
|
98
|
+
```
|
99
|
+
|
100
|
+
### Full Interface
|
101
|
+
|
102
|
+
```
|
103
|
+
writer = SmarterCSV::Writer.new(file_path, options)
|
104
|
+
|
105
|
+
MyModel.find_in_batches(batch_size: 100) do |batch|
|
106
|
+
batch.pluck(:name, :description, :instructor).each do |record|
|
107
|
+
csv_writer << record
|
108
|
+
end
|
109
|
+
|
110
|
+
writer.finalize
|
111
|
+
```
|
112
|
+
|
113
|
+
## Rescue from Exceptions
|
114
|
+
|
115
|
+
While SmarterCSV uses sensible defaults to process the most common CSV files, it will raise exceptions if it can not auto-detect `col_sep`, `row_sep`, or if it encounters other problems. Therefore please rescue from `SmarterCSV::Error`, and handle outliers according to your requirements.
|
116
|
+
|
117
|
+
If you encounter unusual CSV files, please follow the tips in the Troubleshooting section below. You can use the options below to accomodate for unusual formats.
|
118
|
+
|
119
|
+
## Troubleshooting
|
120
|
+
|
121
|
+
In case your CSV file is not being parsed correctly, try to examine it in a text editor. For closer inspection a tool like `hexdump` can help find otherwise hidden control character or byte sequences like [BOMs](https://en.wikipedia.org/wiki/Byte_order_mark).
|
122
|
+
|
123
|
+
```
|
124
|
+
$ hexdump -C spec/fixtures/bom_test_feff.csv
|
125
|
+
00000000 fe ff 73 6f 6d 65 5f 69 64 2c 74 79 70 65 2c 66 |..some_id,type,f|
|
126
|
+
00000010 75 7a 7a 62 6f 78 65 73 0d 0a 34 32 37 36 36 38 |uzzboxes..427668|
|
127
|
+
00000020 30 35 2c 7a 69 7a 7a 6c 65 73 2c 31 32 33 34 0d |05,zizzles,1234.|
|
128
|
+
00000030 0a 33 38 37 35 39 31 35 30 2c 71 75 69 7a 7a 65 |.38759150,quizze|
|
129
|
+
00000040 73 2c 35 36 37 38 0d 0a |s,5678..|
|
130
|
+
```
|
131
|
+
|
132
|
+
## Assumptions / Limitations
|
133
|
+
|
134
|
+
* the escape character is `\`, as on UNIX and Windows systems.
|
135
|
+
* quote charcters around fields are balanced, e.g. valid: `"field"`, invalid: `"field\"`
|
136
|
+
e.g. an escaped `quote_char` does not denote the end of a field.
|
137
|
+
|
138
|
+
|
139
|
+
## NOTES about File Encodings:
|
140
|
+
* if you have a CSV file which contains unicode characters, you can process it as follows:
|
141
|
+
|
142
|
+
```ruby
|
143
|
+
File.open(filename, "r:bom|utf-8") do |f|
|
144
|
+
data = SmarterCSV.process(f);
|
145
|
+
end
|
146
|
+
```
|
147
|
+
* if the CSV file with unicode characters is in a remote location, similarly you need to give the encoding as an option to the `open` call:
|
148
|
+
```ruby
|
149
|
+
require 'open-uri'
|
150
|
+
file_location = 'http://your.remote.org/sample.csv'
|
151
|
+
open(file_location, 'r:utf-8') do |f| # don't forget to specify the UTF-8 encoding!!
|
152
|
+
data = SmarterCSV.process(f)
|
153
|
+
end
|
154
|
+
```
|
155
|
+
|
156
|
+
----------------
|
157
|
+
PREVIOUS: [Introduction](./_introduction.md) | NEXT: [Batch Processing](./batch_processing.md)
|
@@ -0,0 +1,68 @@
|
|
1
|
+
|
2
|
+
### Contents
|
3
|
+
|
4
|
+
* [Introduction](./_introduction.md)
|
5
|
+
* [The Basic API](./basic_api.md)
|
6
|
+
* [**Batch Processing**](././batch_processing.md)
|
7
|
+
* [Configuration Options](./options.md)
|
8
|
+
* [Row and Column Separators](./row_col_sep.md)
|
9
|
+
* [Header Transformations](./header_transformations.md)
|
10
|
+
* [Header Validations](./header_validations.md)
|
11
|
+
* [Data Transformations](./data_transformations.md)
|
12
|
+
* [Value Converters](./value_converters.md)
|
13
|
+
|
14
|
+
--------------
|
15
|
+
|
16
|
+
# Batch Processing
|
17
|
+
|
18
|
+
Processing CSV data in batches (chunks), allows you to parallelize the workload of importing data.
|
19
|
+
This can come in handy when you don't want to slow-down the CSV import of large files.
|
20
|
+
|
21
|
+
Setting the option `chunk_size` sets the max batch size.
|
22
|
+
|
23
|
+
|
24
|
+
## Example 1: How SmarterCSV processes CSV-files as chunks, returning arrays of hashes:
|
25
|
+
Please note how the returned array contains two sub-arrays containing the chunks which were read, each chunk containing 2 hashes.
|
26
|
+
In case the number of rows is not cleanly divisible by `:chunk_size`, the last chunk contains fewer hashes.
|
27
|
+
|
28
|
+
```ruby
|
29
|
+
> pets_by_owner = SmarterCSV.process('/tmp/pets.csv', {:chunk_size => 2, :key_mapping => {:first_name => :first, :last_name => :last}})
|
30
|
+
=> [ [ {:first=>"Dan", :last=>"McAllister", :dogs=>"2"}, {:first=>"Lucy", :last=>"Laweless", :cats=>"5"} ],
|
31
|
+
[ {:first=>"Miles", :last=>"O'Brian", :fish=>"21"}, {:first=>"Nancy", :last=>"Homes", :dogs=>"2", :birds=>"1"} ]
|
32
|
+
]
|
33
|
+
```
|
34
|
+
|
35
|
+
## Example 2: How SmarterCSV processes CSV-files as chunks, and passes arrays of hashes to a given block:
|
36
|
+
Please note how the given block is passed the data for each chunk as the parameter (array of hashes),
|
37
|
+
and how the `process` method returns the number of chunks when called with a block
|
38
|
+
|
39
|
+
```ruby
|
40
|
+
> total_chunks = SmarterCSV.process('/tmp/pets.csv', {:chunk_size => 2, :key_mapping => {:first_name => :first, :last_name => :last}}) do |chunk|
|
41
|
+
chunk.each do |h| # you can post-process the data from each row to your heart's content, and also create virtual attributes:
|
42
|
+
h[:full_name] = [h[:first],h[:last]].join(' ') # create a virtual attribute
|
43
|
+
h.delete(:first) ; h.delete(:last) # remove two keys
|
44
|
+
end
|
45
|
+
puts chunk.inspect # we could at this point pass the chunk to a Resque worker..
|
46
|
+
end
|
47
|
+
|
48
|
+
[{:dogs=>"2", :full_name=>"Dan McAllister"}, {:cats=>"5", :full_name=>"Lucy Laweless"}]
|
49
|
+
[{:fish=>"21", :full_name=>"Miles O'Brian"}, {:dogs=>"2", :birds=>"1", :full_name=>"Nancy Homes"}]
|
50
|
+
=> 2
|
51
|
+
```
|
52
|
+
|
53
|
+
## Example 3: Populate a MongoDB Database in Chunks of 100 records with SmarterCSV:
|
54
|
+
```ruby
|
55
|
+
# using chunks:
|
56
|
+
filename = '/tmp/some.csv'
|
57
|
+
options = {:chunk_size => 100, :key_mapping => {:unwanted_row => nil, :old_row_name => :new_name}}
|
58
|
+
n = SmarterCSV.process(filename, options) do |chunk|
|
59
|
+
# we're passing a block in, to process each resulting hash / row (block takes array of hashes)
|
60
|
+
# when chunking is enabled, there are up to :chunk_size hashes in each chunk
|
61
|
+
MyModel.insert_all( chunk ) # insert up to 100 records at a time
|
62
|
+
end
|
63
|
+
|
64
|
+
=> returns number of chunks we processed
|
65
|
+
```
|
66
|
+
|
67
|
+
----------------
|
68
|
+
PREVIOUS: [The Basic API](./basic_api.md) | NEXT: [Configuration Options](./options.md)
|
@@ -0,0 +1,50 @@
|
|
1
|
+
|
2
|
+
### Contents
|
3
|
+
|
4
|
+
* [Introduction](./_introduction.md)
|
5
|
+
* [The Basic API](./basic_api.md)
|
6
|
+
* [Batch Processing](././batch_processing.md)
|
7
|
+
* [Configuration Options](./options.md)
|
8
|
+
* [Row and Column Separators](./row_col_sep.md)
|
9
|
+
* [Header Transformations](./header_transformations.md)
|
10
|
+
* [Header Validations](./header_validations.md)
|
11
|
+
* [**Data Transformations**](./data_transformations.md)
|
12
|
+
* [Value Converters](./value_converters.md)
|
13
|
+
|
14
|
+
--------------
|
15
|
+
|
16
|
+
# Data Transformations
|
17
|
+
|
18
|
+
SmarterCSV automatically transforms the values in each colum in order to normalize the data.
|
19
|
+
This behavior can be customized or disabled.
|
20
|
+
|
21
|
+
## Remove Empty Values
|
22
|
+
`remove_empty_values` is enabled by default
|
23
|
+
It removes any values which are `nil` or would be empty strings.
|
24
|
+
|
25
|
+
## Convert Values to Numeric
|
26
|
+
`convert_values_to_numeric` is enabled by default.
|
27
|
+
SmarterCSV will convert strings containing Integers or Floats to the appropriate class.
|
28
|
+
|
29
|
+
## Remove Zero Values
|
30
|
+
`remove_zero_values` is disabled by default.
|
31
|
+
When enabled, it removes key/value pairs which have a numeric value equal to zero.
|
32
|
+
|
33
|
+
## Remove Values Matching
|
34
|
+
`remove_values_matching` is disabled by default.
|
35
|
+
When enabled, this can help removing key/value pairs from result hashes which would cause problems.
|
36
|
+
|
37
|
+
e.g.
|
38
|
+
* `remove_values_matching: /^\$0\.0+$/` would remove $0.00
|
39
|
+
* `remove_values_matching: /^#VALUE!$/` would remove errors from Excel spreadsheets
|
40
|
+
|
41
|
+
## Empty Hashes
|
42
|
+
|
43
|
+
It can happen that after all transformations, a row of the CSV file would produce a completely empty hash.
|
44
|
+
|
45
|
+
By default SmarterCSV uses `remove_empty_hashes: true` to remove these empty hashes from the result.
|
46
|
+
|
47
|
+
This can be set to `true`, to keep these empty hashes in the results.
|
48
|
+
|
49
|
+
-------------------
|
50
|
+
PREVIOUS: [Header Validations](./header_validations.md) | NEXT: [Value Converters](./value_converters.md)
|
data/docs/examples.md
ADDED
@@ -0,0 +1,75 @@
|
|
1
|
+
|
2
|
+
### Contents
|
3
|
+
|
4
|
+
* [Introduction](./_introduction.md)
|
5
|
+
* [The Basic API](./basic_api.md)
|
6
|
+
* [Batch Processing](././batch_processing.md)
|
7
|
+
* [Configuration Options](./options.md)
|
8
|
+
* [Row and Column Separators](./row_col_sep.md)
|
9
|
+
* [Header Transformations](./header_transformations.md)
|
10
|
+
* [Header Validations](./header_validations.md)
|
11
|
+
* [Data Transformations](./data_transformations.md)
|
12
|
+
* [Value Converters](./value_converters.md)
|
13
|
+
|
14
|
+
--------------
|
15
|
+
|
16
|
+
# Examples
|
17
|
+
|
18
|
+
Here are some examples to demonstrate the versatility of SmarterCSV.
|
19
|
+
|
20
|
+
**It is generally recommended to rescue `SmarterCSV::Error` or it's sub-classes.**
|
21
|
+
|
22
|
+
By default SmarterCSV determines the `row_sep` and `col_sep` values automatically. In cases where the automatic detection fails, an exception will be raised, e.g. `NoColSepDetected`. Rescuing from these exceptions will make sure that you don't miss processing CSV files, in case users upload CSV files with unexpected formats.
|
23
|
+
|
24
|
+
In rare cases you may have to manually set these values, after going through the troubleshooting procedure described above.
|
25
|
+
|
26
|
+
## Example 1a: How SmarterCSV processes CSV-files as array of hashes:
|
27
|
+
Please note how each hash contains only the keys for columns with non-null values.
|
28
|
+
|
29
|
+
```ruby
|
30
|
+
$ cat pets.csv
|
31
|
+
first name,last name,dogs,cats,birds,fish
|
32
|
+
Dan,McAllister,2,,,
|
33
|
+
Lucy,Laweless,,5,,
|
34
|
+
Miles,O'Brian,,,,21
|
35
|
+
Nancy,Homes,2,,1,
|
36
|
+
$ irb
|
37
|
+
> require 'smarter_csv'
|
38
|
+
=> true
|
39
|
+
> pets_by_owner = SmarterCSV.process('/tmp/pets.csv')
|
40
|
+
=> [ {:first_name=>"Dan", :last_name=>"McAllister", :dogs=>"2"},
|
41
|
+
{:first_name=>"Lucy", :last_name=>"Laweless", :cats=>"5"},
|
42
|
+
{:first_name=>"Miles", :last_name=>"O'Brian", :fish=>"21"},
|
43
|
+
{:first_name=>"Nancy", :last_name=>"Homes", :dogs=>"2", :birds=>"1"}
|
44
|
+
]
|
45
|
+
```
|
46
|
+
|
47
|
+
|
48
|
+
## Example 3: Populate a MySQL or MongoDB Database with SmarterCSV:
|
49
|
+
```ruby
|
50
|
+
# without using chunks:
|
51
|
+
filename = '/tmp/some.csv'
|
52
|
+
options = {:key_mapping => {:unwanted_row => nil, :old_row_name => :new_name}}
|
53
|
+
n = SmarterCSV.process(filename, options) do |array|
|
54
|
+
# we're passing a block in, to process each resulting hash / =row (the block takes array of hashes)
|
55
|
+
# when chunking is not enabled, there is only one hash in each array
|
56
|
+
MyModel.create( array.first )
|
57
|
+
end
|
58
|
+
|
59
|
+
=> returns number of chunks / rows we processed
|
60
|
+
```
|
61
|
+
|
62
|
+
## Example 4: Processing a CSV File, and inserting batch jobs in Sidekiq:
|
63
|
+
```ruby
|
64
|
+
filename = '/tmp/input.csv' # CSV file containing ids or data to process
|
65
|
+
options = { :chunk_size => 100 }
|
66
|
+
n = SmarterCSV.process(filename, options) do |chunk|
|
67
|
+
Sidekiq::Client.push_bulk(
|
68
|
+
'class' => SidekiqIndividualWorkerClass,
|
69
|
+
'args' => chunk,
|
70
|
+
)
|
71
|
+
# OR:
|
72
|
+
# SidekiqBatchWorkerClass.process_async(chunk ) # pass an array of hashes to Sidekiq workers for parallel processing
|
73
|
+
end
|
74
|
+
=> returns number of chunks
|
75
|
+
```
|
@@ -0,0 +1,113 @@
|
|
1
|
+
|
2
|
+
### Contents
|
3
|
+
|
4
|
+
* [Introduction](./_introduction.md)
|
5
|
+
* [The Basic API](./basic_api.md)
|
6
|
+
* [Batch Processing](././batch_processing.md)
|
7
|
+
* [Configuration Options](./options.md)
|
8
|
+
* [Row and Column Separators](./row_col_sep.md)
|
9
|
+
* [**Header Transformations**](./header_transformations.md)
|
10
|
+
* [Header Validations](./header_validations.md)
|
11
|
+
* [Data Transformations](./data_transformations.md)
|
12
|
+
* [Value Converters](./value_converters.md)
|
13
|
+
|
14
|
+
--------------
|
15
|
+
|
16
|
+
# Header Transformations
|
17
|
+
|
18
|
+
By default SmarterCSV assumes that a CSV file has headers, and it automatically normalizes the headers and transforms them into Ruby symbols. You can completely customize or override this (see below).
|
19
|
+
|
20
|
+
## Header Normalization
|
21
|
+
|
22
|
+
When processing the headers, it transforms them into Ruby symbols, stripping extra spaces, lower-casing them and replacing spaces with underscores. e.g. " \t Annual Sales " becomes `:annual_sales`. (see Notes below)
|
23
|
+
|
24
|
+
## Duplicate Headers
|
25
|
+
|
26
|
+
There can be a lot of variation in CSV files. It is possible that a CSV file contains multiple headers with the same name.
|
27
|
+
|
28
|
+
By default SmarterCSV handles duplicate headers by appending numbers 2..n to them.
|
29
|
+
|
30
|
+
Consider this example:
|
31
|
+
|
32
|
+
```
|
33
|
+
$ cat > /tmp/dupe.csv
|
34
|
+
name,name,name
|
35
|
+
Carl,Edward,Sagan
|
36
|
+
```
|
37
|
+
|
38
|
+
When parsing these duplicate headers, SmarterCSV will return:
|
39
|
+
|
40
|
+
```
|
41
|
+
data = SmarterCSV.process('/tmp/dupe.csv')
|
42
|
+
=> [{:name=>"Carl", :name2=>"Edward", :name3=>"Sagan"}]
|
43
|
+
```
|
44
|
+
|
45
|
+
If you want to have an underscore between the header and the number, you can set `duplicate_header_suffix: '_'`.
|
46
|
+
|
47
|
+
```
|
48
|
+
data = SmarterCSV.process('/tmp/dupe.csv', {duplicate_header_suffix: '_'})
|
49
|
+
=> [{:name=>"Carl", :name_2=>"Edward", :name_3=>"Sagan"}]
|
50
|
+
```
|
51
|
+
|
52
|
+
To further disambiguate the headers, you can further use `key_mapping` to assign meaningful names. Please note that the mapping uses the already transformed keys `name_2`, `name_3` as input.
|
53
|
+
|
54
|
+
```
|
55
|
+
options = {
|
56
|
+
duplicate_header_suffix: '_',
|
57
|
+
key_mapping: {
|
58
|
+
name: :first_name,
|
59
|
+
name_2: :middle_name,
|
60
|
+
name_3: :last_name,
|
61
|
+
}
|
62
|
+
}
|
63
|
+
data = SmarterCSV.process('/tmp/dupe.csv', options)
|
64
|
+
=> [{:first_name=>"Carl", :middle_name=>"Edward", :last_name=>"Sagan"}]
|
65
|
+
```
|
66
|
+
|
67
|
+
## Key Mapping
|
68
|
+
|
69
|
+
The above example already illustrates how intermediate keys can be mapped into something different.
|
70
|
+
This transfoms some of the keys in the input, but other keys are still present.
|
71
|
+
|
72
|
+
There is an additional option `remove_unmapped_keys` which can be enabled to only produce the mapped keys in the resulting hashes, and drops any other columns.
|
73
|
+
|
74
|
+
|
75
|
+
### NOTES on Key Mapping:
|
76
|
+
* keys in the header line of the file can be re-mapped to a chosen set of symbols, so the resulting Hashes can be better used internally in your application (e.g. when directly creating MongoDB entries with them)
|
77
|
+
* if you want to completely delete a key, then map it to nil or to '', they will be automatically deleted from any result Hash
|
78
|
+
* if you have input files with a large number of columns, and you want to ignore all columns which are not specifically mapped with :key_mapping, then use option :remove_unmapped_keys => true
|
79
|
+
|
80
|
+
## CSV Files without Headers
|
81
|
+
|
82
|
+
If you have CSV files without headers, it is important to set `headers_in_file: false`, otherwise you'll lose the first data line in your file.
|
83
|
+
You then have to provide `user_provided_headers`, which takes an array of either symbols or strings.
|
84
|
+
|
85
|
+
|
86
|
+
## CSV Files with Headers
|
87
|
+
|
88
|
+
For CSV files with headers, you can either:
|
89
|
+
|
90
|
+
* use the automatic header normalization
|
91
|
+
* map one or more headers into whatever you chose using the `map_headers` option.
|
92
|
+
(if you map a header to `nil`, it will remove that column from the resulting row hash).
|
93
|
+
* completely replace the headers using `user_provided_headers` (please be careful with this powerful option, as it is not robust against changes in input format).
|
94
|
+
* use the original unmodified headers from the CSV file, using `keep_original_headers`. This results in hash keys that are strings, and may be padded with spaces.
|
95
|
+
|
96
|
+
|
97
|
+
# Notes
|
98
|
+
|
99
|
+
### NOTES about CSV Headers:
|
100
|
+
* as this method parses CSV files, it is assumed that the first line of any file will contain a valid header
|
101
|
+
* the first line with the header might be commented out, in which case you will need to set `comment_regexp: /\A#/`
|
102
|
+
* any occurences of :comment_regexp or :row_sep will be stripped from the first line with the CSV header
|
103
|
+
* any of the keys in the header line will be downcased, spaces replaced by underscore, and converted to Ruby symbols before being used as keys in the returned Hashes
|
104
|
+
* you can not combine the :user_provided_headers and :key_mapping options
|
105
|
+
* if the incorrect number of headers are provided via :user_provided_headers, exception SmarterCSV::HeaderSizeMismatch is raised
|
106
|
+
|
107
|
+
### NOTES on improper quotation and unwanted characters in headers:
|
108
|
+
* some CSV files use un-escaped quotation characters inside fields. This can cause the import to break. To get around this, use the `:force_simple_split => true` option in combination with `:strip_chars_from_headers => /[\-"]/` . This will also significantly speed up the import.
|
109
|
+
If you would force a different :quote_char instead (setting it to a non-used character), then the import would be up to 5-times slower than using `:force_simple_split`.
|
110
|
+
|
111
|
+
---------------
|
112
|
+
PREVIOUS: [Row and Column Separators](./row_col_sep.md) | NEXT: [Header Validations](./header_validations.md)
|
113
|
+
|
@@ -0,0 +1,36 @@
|
|
1
|
+
|
2
|
+
### Contents
|
3
|
+
|
4
|
+
* [Introduction](./_introduction.md)
|
5
|
+
* [The Basic API](./basic_api.md)
|
6
|
+
* [Batch Processing](././batch_processing.md)
|
7
|
+
* [Configuration Options](./options.md)
|
8
|
+
* [Row and Column Separators](./row_col_sep.md)
|
9
|
+
* [Header Transformations](./header_transformations.md)
|
10
|
+
* [**Header Validations**](./header_validations.md)
|
11
|
+
* [Data Transformations](./data_transformations.md)
|
12
|
+
* [Value Converters](./value_converters.md)
|
13
|
+
|
14
|
+
--------------
|
15
|
+
|
16
|
+
# Header Validations
|
17
|
+
|
18
|
+
When you are importing data, it can be important to verify that all required data is present, to ensure consistent quality when importing data.
|
19
|
+
|
20
|
+
You can use the `required_keys` option to specify an array of hash keys that you require to be present at a minimum for every data row (after header transformation).
|
21
|
+
|
22
|
+
If these keys are not present, `SmarterCSV::MissingKeys` will be raised to inform you of the data inconsistency.
|
23
|
+
|
24
|
+
## Example
|
25
|
+
|
26
|
+
```ruby
|
27
|
+
options = {
|
28
|
+
required_keys: [:source_account, :destination_account, :amount]
|
29
|
+
}
|
30
|
+
data = SmarterCSV.process("/tmp/transactions.csv", options)
|
31
|
+
|
32
|
+
=> this will raise SmarterCSV::MissingKeys if any row does not contain these three keys
|
33
|
+
```
|
34
|
+
|
35
|
+
----------------
|
36
|
+
PREVIOUS: [Header Transformations](./header_transformations.md) | NEXT: [Data Transformations](./data_transformations.md)
|
data/docs/options.md
ADDED
@@ -0,0 +1,98 @@
|
|
1
|
+
|
2
|
+
### Contents
|
3
|
+
|
4
|
+
* [Introduction](./_introduction.md)
|
5
|
+
* [The Basic API](./basic_api.md)
|
6
|
+
* [Batch Processing](././batch_processing.md)
|
7
|
+
* [**Configuration Options**](./options.md)
|
8
|
+
* [Row and Column Separators](./row_col_sep.md)
|
9
|
+
* [Header Transformations](./header_transformations.md)
|
10
|
+
* [Header Validations](./header_validations.md)
|
11
|
+
* [Data Transformations](./data_transformations.md)
|
12
|
+
* [Value Converters](./value_converters.md)
|
13
|
+
|
14
|
+
--------------
|
15
|
+
|
16
|
+
# Configuration Options
|
17
|
+
|
18
|
+
## CSV Writing
|
19
|
+
|
20
|
+
| Option | Default | Explanation |
|
21
|
+
---------------------------------------------------------------------------------------------------------------------------------
|
22
|
+
| :row_sep | $/ | Separates rows; Defaults to your OS row separator. `/n` on UNIX, `/r/n` oon Windows |
|
23
|
+
| :col_sep | "," | Separates each value in a row |
|
24
|
+
| :quote_char | '"' | |
|
25
|
+
| :force_quotes | false | Forces each individual value to be quoted |
|
26
|
+
| :discover_headers | true | Automatically detects all keys in the input before writing the header |
|
27
|
+
| | | This can be disabled by providing `headers` or `map_headers` options. |
|
28
|
+
| :headers | [] | You can provide the specific list of keys from the input you'd like to be used as headers in the CSV file |
|
29
|
+
| :map_headers | {} | Similar to `headers`, but also maps each desired key to a user-specified value that is uesd as the header. |
|
30
|
+
|
|
31
|
+
|
32
|
+
## CSV Reading
|
33
|
+
|
34
|
+
| Option | Default | Explanation |
|
35
|
+
---------------------------------------------------------------------------------------------------------------------------------
|
36
|
+
| :chunk_size | nil | if set, determines the desired chunk-size (defaults to nil, no chunk processing) |
|
37
|
+
| | | |
|
38
|
+
| :file_encoding | utf-8 | Set the file encoding eg.: 'windows-1252' or 'iso-8859-1' |
|
39
|
+
| :invalid_byte_sequence | '' | what to replace invalid byte sequences with |
|
40
|
+
| :force_utf8 | false | force UTF-8 encoding of all lines (including headers) in the CSV file |
|
41
|
+
| :skip_lines | nil | how many lines to skip before the first line or header line is processed |
|
42
|
+
| :comment_regexp | nil | regular expression to ignore comment lines (see NOTE on CSV header), e.g./\A#/ |
|
43
|
+
---------------------------------------------------------------------------------------------------------------------------------
|
44
|
+
| :col_sep | :auto | column separator (default was ',') |
|
45
|
+
| :force_simple_split | false | force simple splitting on :col_sep character for non-standard CSV-files. |
|
46
|
+
| | | e.g. when :quote_char is not properly escaped |
|
47
|
+
| :row_sep | :auto | row separator or record separator (previous default was system's $/ , which defaulted to "\n") |
|
48
|
+
| | | This can also be set to :auto, but will process the whole cvs file first (slow!) |
|
49
|
+
| :auto_row_sep_chars | 500 | How many characters to analyze when using `:row_sep => :auto`. nil or 0 means whole file. |
|
50
|
+
| :quote_char | '"' | quotation character |
|
51
|
+
---------------------------------------------------------------------------------------------------------------------------------
|
52
|
+
| :headers_in_file | true | Whether or not the file contains headers as the first line. |
|
53
|
+
| | | Important if the file does not contain headers, |
|
54
|
+
| | | otherwise you would lose the first line of data. |
|
55
|
+
| :duplicate_header_suffix | '' | Adds numbers to duplicated headers and separates them by the given suffix. |
|
56
|
+
| | | Set this to nil to raise `DuplicateHeaders` error instead (previous behavior) |
|
57
|
+
| :user_provided_headers | nil | *careful with that axe!* |
|
58
|
+
| | | user provided Array of header strings or symbols, to define |
|
59
|
+
| | | what headers should be used, overriding any in-file headers. |
|
60
|
+
| | | You can not combine the :user_provided_headers and :key_mapping options |
|
61
|
+
| :remove_empty_hashes | true | remove / ignore any hashes which don't have any key/value pairs or all empty values |
|
62
|
+
| :verbose | false | print out line number while processing (to track down problems in input files) |
|
63
|
+
| :with_line_numbers | false | add :csv_line_number to each data hash |
|
64
|
+
---------------------------------------------------------------------------------------------------------------------------------
|
65
|
+
|
66
|
+
Additional 1.x Options which may be replaced in 2.0
|
67
|
+
|
68
|
+
There have been a lot of 1-offs and feature creep around these options, and going forward we'll strive to have a simpler, but more flexible way to address these features.
|
69
|
+
|
70
|
+
|
71
|
+
| Option | Default | Explanation |
|
72
|
+
---------------------------------------------------------------------------------------------------------------------------------
|
73
|
+
| :key_mapping | nil | a hash which maps headers from the CSV file to keys in the result hash |
|
74
|
+
| :silence_missing_keys | false | ignore missing keys in `key_mapping` |
|
75
|
+
| | | if set to true: makes all mapped keys optional |
|
76
|
+
| | | if given an array, makes only the keys listed in it optional |
|
77
|
+
| :required_keys | nil | An array. Specify the required names AFTER header transformation. |
|
78
|
+
| :required_headers | nil | (DEPRECATED / renamed) Use `required_keys` instead |
|
79
|
+
| | | or an exception is raised No validation if nil is given. |
|
80
|
+
| :remove_unmapped_keys | false | when using :key_mapping option, should non-mapped keys / columns be removed? |
|
81
|
+
| :downcase_header | true | downcase all column headers |
|
82
|
+
| :strings_as_keys | false | use strings instead of symbols as the keys in the result hashes |
|
83
|
+
| :strip_whitespace | true | remove whitespace before/after values and headers |
|
84
|
+
| :keep_original_headers | false | keep the original headers from the CSV-file as-is. |
|
85
|
+
| | | Disables other flags manipulating the header fields. |
|
86
|
+
| :strip_chars_from_headers | nil | RegExp to remove extraneous characters from the header line (e.g. if headers are quoted) |
|
87
|
+
---------------------------------------------------------------------------------------------------------------------------------
|
88
|
+
| :value_converters | nil | supply a hash of :header => KlassName; the class needs to implement self.convert(val)|
|
89
|
+
| :remove_empty_values | true | remove values which have nil or empty strings as values |
|
90
|
+
| :remove_zero_values | false | remove values which have a numeric value equal to zero / 0 |
|
91
|
+
| :remove_values_matching | nil | removes key/value pairs if value matches given regular expressions. e.g.: |
|
92
|
+
| | | /^\$0\.0+$/ to match $0.00 , or /^#VALUE!$/ to match errors in Excel spreadsheets |
|
93
|
+
| :convert_values_to_numeric | true | converts strings containing Integers or Floats to the appropriate class |
|
94
|
+
| | | also accepts either {:except => [:key1,:key2]} or {:only => :key3} |
|
95
|
+
---------------------------------------------------------------------------------------------------------------------------------
|
96
|
+
|
97
|
+
-------------
|
98
|
+
PREVIOUS: [Batch Processing](./batch_processing.md) | NEXT: [Row and Column Separators](./row_col_sep.md)
|