smarter_csv 1.13.0 → 1.14.0

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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: c28d21a143e743de4b21d8ad93d860b1d51424e525e9ec0a73bb640b170d9823
4
- data.tar.gz: e7a16ae8494196b85d9a196d071f09b302583c9ef3a414f09f5ad6ae1f11c29b
3
+ metadata.gz: 7f7308ee39fc18fb93f23273b32559ae83139375bfc84c975a1b6cf048368a5e
4
+ data.tar.gz: a50d9ea0b40bf28adc829613d8d0b2744018b708453b96cc339653688a1c1f40
5
5
  SHA512:
6
- metadata.gz: 319ee5aed33630e9670a1c95cc8da6fd57df9d1d7db57a00af79c1e5c10de56b4e9054c86b6b462ebdc693513a79aff2c881a1ede00ad28e5da58768b4a6f2cf
7
- data.tar.gz: 6b36378d3a15ed9065c697f56f2cafc359d2c746e5796780a276c1a87c6a04be38616205f31ec9341412f3c9a4f52d150ce4ef95c0e76f340368d5683b1452e6
6
+ metadata.gz: baf9bad5261b6ab75d4d49fc7b0044536a9977955ef01d38b9d9431478649be8481a378a4b988b6091b7f2c5ba5f6c2a8899dfc2143f2bd11c834386453024d1
7
+ data.tar.gz: 7283acb30cbdde33c463f369a619cc93235ea2931153babdcaedabe468cf50e198ab0264e9c70ee166a81cc072b44ab874d89e4de835379495155784b7a31035
data/CHANGELOG.md CHANGED
@@ -1,6 +1,12 @@
1
1
 
2
2
  # SmarterCSV 1.x Change Log
3
3
 
4
+ ## 1.14.0 (2025-04-07)
5
+ * adding advanced configuration options for writing CSV files. ([issue 297](https://github.com/tilo/smarter_csv/issues/297) thanks to Robert Reiz, [issue 296](https://github.com/tilo/smarter_csv/issues/296))
6
+
7
+ ## 1.13.1 (2024-12-12)
8
+ * fix bug with SmarterCSV.generate with `force_quotes: true` ([issue 294](https://github.com/tilo/smarter_csv/issues/294))
9
+
4
10
  ## 1.13.0 (2024-11-06) ⚡ POTENTIALLY BREAKING ⚡
5
11
 
6
12
  CHANGED DEFAULT BEHAVIOR
@@ -38,7 +44,7 @@
38
44
 
39
45
  IF you set `user_provided_headers` and the file has a header, then provide `headers_in_file: true` to avoid getting that extra record.
40
46
 
41
- * handling of numeric columns with leading zeroes, e.g. ZIP codes. ([issue #151](https://github.com/tilo/smarter_csv/issues/151) thanks to David Moles). `convert_values_to_numeric: { except: [:zip] }` will now return a string for that column instead.
47
+ * improved documentation for handling of numeric columns with leading zeroes, e.g. ZIP codes. ([issue #151](https://github.com/tilo/smarter_csv/issues/151) thanks to David Moles). `convert_values_to_numeric: { except: [:zip] }` will return a string for that column instead (since version 1.10.x)
42
48
 
43
49
  ## 1.12.1 (2024-07-10)
44
50
  * Improved column separator detection by ignoring quoted sections [#276](https://github.com/tilo/smarter_csv/pull/276) (thanks to Nicolas Castellanos)
data/CONTRIBUTORS.md CHANGED
@@ -58,3 +58,4 @@ A Big Thank you to everyone who filed issues, sent comments, and who contributed
58
58
  * [Simon Rentzke](https://github.com/simonrentzke)
59
59
  * [Randall B](https://github.com/randall-coding)
60
60
  * [Matthew Kennedy](https://github.com/MattKitmanLabs)
61
+ * [Robert Reiz](https://github.com/reiz)
data/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
 
2
2
  # SmarterCSV
3
3
 
4
- [![codecov](https://codecov.io/gh/tilo/smarter_csv/branch/main/graph/badge.svg?token=1L7OD80182)](https://codecov.io/gh/tilo/smarter_csv) [![Gem Version](https://badge.fury.io/rb/smarter_csv.svg)](http://badge.fury.io/rb/smarter_csv)
4
+ ![Gem Version](https://img.shields.io/gem/v/smarter_csv) [![codecov](https://codecov.io/gh/tilo/smarter_csv/branch/main/graph/badge.svg?token=1L7OD80182)](https://codecov.io/gh/tilo/smarter_csv) [View on RubyGems](https://rubygems.org/gems/smarter_csv) [View on RubyToolbox](https://www.ruby-toolbox.com/search?q=smarter_csv)
5
5
 
6
6
  SmarterCSV provides a convenient interface for reading and writing CSV files and data.
7
7
 
@@ -35,7 +35,8 @@ Or install it yourself as:
35
35
  # Documentation
36
36
 
37
37
  * [Introduction](docs/_introduction.md)
38
- * [The Basic API](docs/basic_api.md)
38
+ * [The Basic Read API](docs/basic_read_api.md)
39
+ * [The Basic Write API](docs/basic_write_api.md)
39
40
  * [Batch Processing](./docs/batch_processing.md)
40
41
  * [Configuration Options](docs/options.md)
41
42
  * [Row and Column Separators](docs/row_col_sep.md)
@@ -45,10 +46,10 @@ Or install it yourself as:
45
46
  * [Value Converters](docs/value_converters.md)
46
47
 
47
48
  # Articles
48
- * [Parsing CSV Files in Ruby with SmarterCSV](https://tilo-sloboda.medium.com/parsing-csv-files-in-ruby-with-smartercsv-6ce66fb6cf38)
49
- * [Processing 1.4 Million CSV Records in Ruby, fast ](https://lcx.wien/blog/processing-14-million-csv-records-in-ruby/)
50
- * [Speeding up CSV parsing with parallel processing](http://xjlin0.github.io/tech/2015/05/25/faster-parsing-csv-with-parallel-processing)
51
- * [The original post](http://www.unixgods.org/Ruby/process_csv_as_hashes.html) that started SmarterCSV
49
+ * [Parsing CSV Files in Ruby with SmarterCSV](https://tilo-sloboda.medium.com/parsing-csv-files-in-ruby-with-smartercsv-6ce66fb6cf38)
50
+ * [Processing 1.4 Million CSV Records in Ruby, fast ](https://lcx.wien/blog/processing-14-million-csv-records-in-ruby/)
51
+ * [Faster Parsing CSV with Parallel Processing](http://xjlin0.github.io/tech/2015/05/25/faster-parsing-csv-with-parallel-processing) by [Jack lin](https://github.com/xjlin0/)
52
+ * [The original post](http://www.unixgods.org/Ruby/process_csv_as_hashes.html) that started SmarterCSV
52
53
 
53
54
  # [ChangeLog](./CHANGELOG.md)
54
55
 
@@ -2,7 +2,8 @@
2
2
  ### Contents
3
3
 
4
4
  * [**Introduction**](./_introduction.md)
5
- * [The Basic API](./basic_api.md)
5
+ * [The Basic Read API](./basic_read_api.md)
6
+ * [The Basic Write API](./basic_write_api.md)
6
7
  * [Batch Processing](././batch_processing.md)
7
8
  * [Configuration Options](./options.md)
8
9
  * [Row and Column Separators](./row_col_sep.md)
@@ -53,4 +54,4 @@ The CSV processing also needed to be robust against variations in the input data
53
54
  (planned feature)
54
55
 
55
56
  ---------------
56
- PREVIOUS [README](../README.md) | NEXT: [The Basic API](./basic_api.md)
57
+ PREVIOUS [README](../README.md) | NEXT: [The Basic Read API](./basic_read_api.md)
@@ -2,7 +2,8 @@
2
2
  ### Contents
3
3
 
4
4
  * [Introduction](./_introduction.md)
5
- * [**The Basic API**](./basic_api.md)
5
+ * [**The Basic Read API**](./basic_read_api.md)
6
+ * [The Basic Write API](./basic_write_api.md)
6
7
  * [Batch Processing](././batch_processing.md)
7
8
  * [Configuration Options](./options.md)
8
9
  * [Row and Column Separators](./row_col_sep.md)
@@ -70,46 +71,6 @@ It cal also be used with a block:
70
71
  This allows you access to the internal state of the `reader` instance after processing.
71
72
 
72
73
 
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
74
  ## Rescue from Exceptions
114
75
 
115
76
  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.
@@ -154,4 +115,4 @@ $ hexdump -C spec/fixtures/bom_test_feff.csv
154
115
  ```
155
116
 
156
117
  ----------------
157
- PREVIOUS: [Introduction](./_introduction.md) | NEXT: [Batch Processing](./batch_processing.md)
118
+ PREVIOUS: [Introduction](./_introduction.md) | NEXT: [The Basic Write API](./basic_write_api.md)
@@ -0,0 +1,160 @@
1
+
2
+ ### Contents
3
+
4
+ * [Introduction](./_introduction.md)
5
+ * [The Basic Read API](./basic_read_api.md)
6
+ * [**The Basic Write API**](./basic_write_api.md)
7
+ * [Batch Processing](././batch_processing.md)
8
+ * [Configuration Options](./options.md)
9
+ * [Row and Column Separators](./row_col_sep.md)
10
+ * [Header Transformations](./header_transformations.md)
11
+ * [Header Validations](./header_validations.md)
12
+ * [Data Transformations](./data_transformations.md)
13
+ * [Value Converters](./value_converters.md)
14
+
15
+ --------------
16
+
17
+ # SmarterCSV Basic Write API
18
+
19
+ Let's explore the basic API for 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 writer instance after processing.
20
+
21
+ ## Writing CSV Files
22
+
23
+ To generate a CSV file, we use the `<<` operator to append new data to the file.
24
+
25
+ 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 in order to create a file.
26
+
27
+ ### Auto-Discovery of Headers
28
+
29
+ By default, the `SmarterCSV::Writer` discovers all keys that are present in the input data, and as they become know, appends them to the CSV headers. This ensures that all data will be included in the output CSV file.
30
+
31
+ If you want to customize the output file, or only include select headers, check the section about Advanced Features below.
32
+
33
+ ### Auto-Quoting of Problematic Values
34
+
35
+ CSV files use some special characters that are important for the CSV format to function:
36
+ * @row_sep : typically `\n` the carriage return
37
+ * @col_sep : typically `,` the comma
38
+ * @quote_char : typically `"` the double-quote
39
+
40
+ When your data for a given field in a CSV row contains either of these characters, we need to prevent them to break the CSV file format.
41
+
42
+ `SmarterCSV::Writer` automatically detects if a field contains either of these three characters. If a field contains the `@quote_char`, it will be prefixed by another `@qoute_char` as per CSV conventions.
43
+ In either case the corresponding field will be put in double-quotes.
44
+
45
+
46
+ ### Simplified Interface
47
+
48
+ The simplified interface takes a block:
49
+
50
+ ```
51
+ SmarterCSV.generate(filename, options) do |csv_writer|
52
+
53
+ MyModel.find_in_batches(batch_size: 100) do |batch|
54
+ batch.pluck(:name, :description, :instructor).each do |record|
55
+ csv_writer << record
56
+ end
57
+ end
58
+
59
+ end
60
+ ```
61
+
62
+ ### Full Interface
63
+
64
+ ```
65
+ writer = SmarterCSV::Writer.new(file_path, options)
66
+
67
+ MyModel.find_in_batches(batch_size: 100) do |batch|
68
+ batch.pluck(:name, :description, :instructor).each do |record|
69
+ csv_writer << record
70
+ end
71
+
72
+ writer.finalize
73
+ ```
74
+
75
+ ## Advanced Features: Customizing the Output Format
76
+
77
+ You can customize the output format through different features.
78
+
79
+ In the options, you can pass-in either of these parameters to customize your output format.
80
+ * `headers`, which limits the CSV headers to just the specified list.
81
+ * `map_header`, which maps a given list of Hash keys to custom strings, and limits the CSV headers to just those.
82
+ * `value_converters`, which specifies a hash with more advanced value transformations.
83
+
84
+ ### Limited Headers
85
+
86
+ You can use the `headers` option to limit the CSV headers to only a sub-set of Hash keys from your data.
87
+ This will switch-off the automatic detection of headers, and limit the CSV output file to only the CSV headers you provide in this option.
88
+
89
+
90
+ ### Mapping Headers
91
+
92
+ Similar to the `headers` option, you can define `map_headers` in order to rename a given set of Hash keys to some custom strings in order to rename them in the CSV header. This will switch-off the automatic detection of headers.
93
+
94
+
95
+ ### Per Key Value Converters
96
+
97
+
98
+ Using per-key value converters, you can control how specific hash keys in your data are converted in the output.
99
+
100
+ Example 1:
101
+
102
+ ```
103
+ options = {
104
+ value_converters: {
105
+ active: ->(v) { !!v ? 'YES' : 'NO' },
106
+ }
107
+ }
108
+ ```
109
+
110
+ This maps the boolean value of the hash key `:active` into strings `"YES"`, `"NO"`.
111
+
112
+ Example 2:
113
+
114
+ ```
115
+ options = {
116
+ value_converters: {
117
+ active: ->(v) { !!v ? '✅' : '❌' },
118
+ balance: ->(v) do
119
+ case v
120
+ when Float
121
+ '$%.2f' % v.round(2)
122
+ when Integer
123
+ "$#{v}"
124
+ else
125
+ v.to_s
126
+ end
127
+ end,
128
+ }
129
+ }
130
+ ```
131
+
132
+ This maps the hash key `:balance` to a string. Floats are rounded and displayed with 2 decimals and prefixed by `$`. Integers are prefixed by `$`.
133
+ The boolean value of the key `:active` is mapped into an emoji.
134
+
135
+ ### Global Value Converters
136
+
137
+ You can also use the special keyword `:_all` to define transformations that are applied to each field of the CSV file.
138
+
139
+ ```
140
+ options = {
141
+ value_converters: {
142
+ disable_auto_quoting: true, # ⚠️ Important: turn off auto-quoting because we're messing with it below
143
+ active: ->(v) { !!v ? 'YES' : 'NO' },
144
+ _all: ->(k, v) { v.is_a?(String) ? "\"#{v}\"" : v } # only double-quote string fields
145
+ }
146
+ }
147
+ ```
148
+
149
+ Using the `:_all` keyword, you can set up rules to convert all hash keys. This is applied after all per-key conversions are made.
150
+
151
+ This example puts double-quotes around all String-value data, but leaves other types unchanged.
152
+
153
+ Note that when you're customizing putting quote-chars around fields, you need to `disable_auto_quoting`.
154
+
155
+ ## More Examples
156
+
157
+ Check out the [RSpec tests](../spec/smarter_csv/writer_spec.rb) for more examples.
158
+
159
+ ----------------
160
+ PREVIOUS: [The Basic Read API](./basic_read_api.md) | NEXT: [Batch Processing](./batch_processing.md)
@@ -2,7 +2,8 @@
2
2
  ### Contents
3
3
 
4
4
  * [Introduction](./_introduction.md)
5
- * [The Basic API](./basic_api.md)
5
+ * [The Basic Read API](./basic_read_api.md)
6
+ * [The Basic Write API](./basic_write_api.md)
6
7
  * [**Batch Processing**](././batch_processing.md)
7
8
  * [Configuration Options](./options.md)
8
9
  * [Row and Column Separators](./row_col_sep.md)
@@ -65,4 +66,4 @@ and how the `process` method returns the number of chunks when called with a blo
65
66
  ```
66
67
 
67
68
  ----------------
68
- PREVIOUS: [The Basic API](./basic_api.md) | NEXT: [Configuration Options](./options.md)
69
+ PREVIOUS: [The Basic Write API](./basic_write_api.md) | NEXT: [Configuration Options](./options.md)
@@ -2,7 +2,8 @@
2
2
  ### Contents
3
3
 
4
4
  * [Introduction](./_introduction.md)
5
- * [The Basic API](./basic_api.md)
5
+ * [The Basic Read API](./basic_read_api.md)
6
+ * [The Basic Write API](./basic_write_api.md)
6
7
  * [Batch Processing](././batch_processing.md)
7
8
  * [Configuration Options](./options.md)
8
9
  * [Row and Column Separators](./row_col_sep.md)
data/docs/examples.md CHANGED
@@ -2,7 +2,8 @@
2
2
  ### Contents
3
3
 
4
4
  * [Introduction](./_introduction.md)
5
- * [The Basic API](./basic_api.md)
5
+ * [The Basic Read API](./basic_read_api.md)
6
+ * [The Basic Write API](./basic_write_api.md)
6
7
  * [Batch Processing](././batch_processing.md)
7
8
  * [Configuration Options](./options.md)
8
9
  * [Row and Column Separators](./row_col_sep.md)
@@ -2,7 +2,8 @@
2
2
  ### Contents
3
3
 
4
4
  * [Introduction](./_introduction.md)
5
- * [The Basic API](./basic_api.md)
5
+ * [The Basic Read API](./basic_read_api.md)
6
+ * [The Basic Write API](./basic_write_api.md)
6
7
  * [Batch Processing](././batch_processing.md)
7
8
  * [Configuration Options](./options.md)
8
9
  * [Row and Column Separators](./row_col_sep.md)
@@ -81,8 +82,8 @@ There is an additional option `remove_unmapped_keys` which can be enabled to onl
81
82
 
82
83
  ## CSV Files without Headers
83
84
 
84
- 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.
85
- You then have to provide `user_provided_headers`, which takes an array of either symbols or strings.
85
+ 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.
86
+ You then have to provide `user_provided_headers`, which takes an array of either symbols or strings. Versions >1.13 now automatically set `headers_in_file: false` if you provide `user_provided_headers`. Also see next paragraph.
86
87
 
87
88
 
88
89
  ## CSV Files with Headers
@@ -93,6 +94,7 @@ For CSV files with headers, you can either:
93
94
  * map one or more headers into whatever you chose using the `map_headers` option.
94
95
  (if you map a header to `nil`, it will remove that column from the resulting row hash).
95
96
  * 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).
97
+ When you use `user_provided_headers`, versions >1.13 will set `headers_in_file: false` -- so if you replace the headers for a file that has headers, you must set `headers_in_file: true` to override this and ignore the header row.
96
98
  * 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.
97
99
 
98
100
 
@@ -104,11 +106,10 @@ For CSV files with headers, you can either:
104
106
  * any occurences of :comment_regexp or :row_sep will be stripped from the first line with the CSV header
105
107
  * 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
106
108
  * you can not combine the :user_provided_headers and :key_mapping options
107
- * if the incorrect number of headers are provided via :user_provided_headers, exception SmarterCSV::HeaderSizeMismatch is raised
109
+ * if the incorrect number of headers are provided via :user_provided_headers, versions >1.13 will automatically add column names `column_N` for additional unexpected columns. If you want to raise an error instead, add option `strict: true`, and it will raise `SmarterCSV::HeaderSizeMismatch`.
108
110
 
109
111
  ### NOTES on improper quotation and unwanted characters in headers:
110
- * 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.
111
- 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`.
112
+ * some CSV files use un-escaped quotation characters inside fields. This can cause the import to break. To get around this, set the `quote_char` to something different, e.g. `quote_char: "%"`, or try setting `:strip_chars_from_headers => /[\-"]/`
112
113
 
113
114
  ---------------
114
115
  PREVIOUS: [Row and Column Separators](./row_col_sep.md) | NEXT: [Header Validations](./header_validations.md)
@@ -2,7 +2,8 @@
2
2
  ### Contents
3
3
 
4
4
  * [Introduction](./_introduction.md)
5
- * [The Basic API](./basic_api.md)
5
+ * [The Basic Read API](./basic_read_api.md)
6
+ * [The Basic Write API](./basic_write_api.md)
6
7
  * [Batch Processing](././batch_processing.md)
7
8
  * [Configuration Options](./options.md)
8
9
  * [Row and Column Separators](./row_col_sep.md)
data/docs/options.md CHANGED
@@ -2,7 +2,8 @@
2
2
  ### Contents
3
3
 
4
4
  * [Introduction](./_introduction.md)
5
- * [The Basic API](./basic_api.md)
5
+ * [The Basic Read API](./basic_read_api.md)
6
+ * [The Basic Write API](./basic_write_api.md)
6
7
  * [Batch Processing](././batch_processing.md)
7
8
  * [**Configuration Options**](./options.md)
8
9
  * [Row and Column Separators](./row_col_sep.md)
@@ -20,14 +21,18 @@
20
21
  | Option | Default | Explanation |
21
22
  ---------------------------------------------------------------------------------------------------------------------------------
22
23
  | :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 | '"' | |
24
+ | :col_sep | "," | Separates each value in a row |
25
+ | :quote_char | '"' | To quote CSV fields. |
25
26
  | :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
27
  | :headers | [] | You can provide the specific list of keys from the input you'd like to be used as headers in the CSV file |
28
+ | | | ⚠️ This disables automatic header detection! |
29
29
  | :map_headers | {} | Similar to `headers`, but also maps each desired key to a user-specified value that is uesd as the header. |
30
- |
30
+ | | | ⚠️ This disables automatic header detection! |
31
+ | :discover_headers | true | Automatically detects all keys in the input before writing the header |
32
+ | | | Do not manually set this to `false`. ⚠️ |
33
+ | | | But you can set this to `true` when using `map_headers` option. |
34
+ | :disable_auto_quoting | false | To manually disable auto-quoting of special characters. ⚠️ Be careful with this! |
35
+
31
36
 
32
37
  ## CSV Reading
33
38
 
@@ -41,9 +46,7 @@
41
46
  | :skip_lines | nil | how many lines to skip before the first line or header line is processed |
42
47
  | :comment_regexp | nil | regular expression to ignore comment lines (see NOTE on CSV header), e.g./\A#/ |
43
48
  ---------------------------------------------------------------------------------------------------------------------------------
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 |
49
+ | :col_sep | :auto | column separator (default was ',') |
47
50
  | :row_sep | :auto | row separator or record separator (previous default was system's $/ , which defaulted to "\n") |
48
51
  | | | This can also be set to :auto, but will process the whole cvs file first (slow!) |
49
52
  | :auto_row_sep_chars | 500 | How many characters to analyze when using `:row_sep => :auto`. nil or 0 means whole file. |
data/docs/row_col_sep.md CHANGED
@@ -2,7 +2,8 @@
2
2
  ### Contents
3
3
 
4
4
  * [Introduction](./_introduction.md)
5
- * [The Basic API](./basic_api.md)
5
+ * [The Basic Read API](./basic_read_api.md)
6
+ * [The Basic Write API](./basic_write_api.md)
6
7
  * [Batch Processing](././batch_processing.md)
7
8
  * [Configuration Options](./options.md)
8
9
  * [**Row and Column Separators**](./row_col_sep.md)
@@ -2,7 +2,8 @@
2
2
  ### Contents
3
3
 
4
4
  * [Introduction](./_introduction.md)
5
- * [The Basic API](./basic_api.md)
5
+ * [The Basic Read API](./basic_read_api.md)
6
+ * [The Basic Write API](./basic_write_api.md)
6
7
  * [Batch Processing](././batch_processing.md)
7
8
  * [Configuration Options](./options.md)
8
9
  * [Row and Column Separators](./row_col_sep.md)
@@ -13,7 +14,7 @@
13
14
 
14
15
  --------------
15
16
 
16
- # Using Value Converters
17
+ # Using Value Converters for Reading CSV
17
18
 
18
19
  Value Converters allow you to do custom transformations specific rows, to help you massage the data so it fits the expectations of your down-stream process, such as creating a DB record.
19
20
 
@@ -20,7 +20,6 @@ module SmarterCSV
20
20
  downcase_header: true,
21
21
  duplicate_header_suffix: '', # was: nil,
22
22
  file_encoding: 'utf-8',
23
- force_simple_split: false,
24
23
  force_utf8: false,
25
24
  headers_in_file: true,
26
25
  invalid_byte_sequence: '',
@@ -88,7 +88,9 @@ module SmarterCSV
88
88
 
89
89
  # Check for unclosed quotes at the end of the line
90
90
  if in_quotes
91
+ # :nocov:
91
92
  raise MalformedCSV, "Unclosed quoted field detected in line: #{line}"
93
+ # :nocov:
92
94
  end
93
95
 
94
96
  # Process the remaining field
@@ -112,7 +112,9 @@ module SmarterCSV
112
112
  raise MalformedCSV, "Unclosed quoted field detected in multiline data"
113
113
  else
114
114
  # Quotes are balanced; proceed without raising an error.
115
+ # :nocov:
115
116
  break
117
+ # :nocov:
116
118
  end
117
119
  end
118
120
  end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module SmarterCSV
4
- VERSION = "1.13.0"
4
+ VERSION = "1.14.0"
5
5
  end
@@ -1,15 +1,17 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require 'tempfile'
4
+
3
5
  module SmarterCSV
4
6
  #
5
7
  # Generate CSV files
6
8
  #
7
9
  # Create an instance of the Writer class with the filename and options.
8
- # call `<<` one or mulltiple times to append data to the file.
10
+ # call `<<` one or multiple times to append data to the file.
9
11
  # call `finalize` to save the file.
10
12
  #
11
13
  # The `<<` method can take different arguments:
12
- # * a signle Hash
14
+ # * a single Hash
13
15
  # * an array of Hashes
14
16
  # * nested arrays of arrays of Hashes
15
17
  #
@@ -29,6 +31,7 @@ module SmarterCSV
29
31
  # headers : defaults to []
30
32
  # force_quotes: defaults to false
31
33
  # map_headers: defaults to {}, can be a hash of key -> value mappings
34
+ # value_converters: optional hash of key -> lambda to control serialization
32
35
 
33
36
  # IMPORTANT NOTES:
34
37
  # * Data hashes could contain strings or symbols as keys.
@@ -41,30 +44,32 @@ module SmarterCSV
41
44
  def initialize(file_path, options = {})
42
45
  @options = options
43
46
 
44
- @row_sep = options[:row_sep] || $/ # Defaults to system's row separator. RFC4180 "\r\n"
47
+ @row_sep = options[:row_sep] || $/
45
48
  @col_sep = options[:col_sep] || ','
46
49
  @quote_char = options[:quote_char] || '"'
47
50
  @force_quotes = options[:force_quotes] == true
48
- @discover_headers = true # defaults to true
51
+ @disable_auto_quoting = options[:disable_auto_quoting] == true
52
+ @value_converters = options[:value_converters] || {}
53
+ @map_all_keys = @value_converters.has_key?(:_all)
54
+ @mapped_keys = @value_converters.keys - [:_all]
55
+
56
+ @discover_headers = true
49
57
  if options.has_key?(:discover_headers)
50
- # passing in the option overrides the default behavior
51
- @discover_headers = options[:discover_headers] == true
58
+ @discover_headers = options[:discover_headers] == true # ⚠️ this option should not be exposed
52
59
  else
53
- # disable discover_headers when headers are given explicitly
54
60
  @discover_headers = !(options.has_key?(:map_headers) || options.has_key?(:headers))
55
61
  end
56
- @headers = [] # start with empty headers
57
- @headers = options[:headers] if options.has_key?(:headers) # unless explicitly given
62
+
63
+ @headers = []
64
+ @headers = options[:headers] if options.has_key?(:headers)
58
65
  @headers = options[:map_headers].keys if options.has_key?(:map_headers) && !options.has_key?(:headers)
59
66
  @map_headers = options[:map_headers] || {}
60
67
 
61
68
  @output_file = File.open(file_path, 'w+')
62
- # hidden state:
63
69
  @temp_file = Tempfile.new('tempfile', '/tmp')
64
70
  @quote_regex = Regexp.union(@col_sep, @row_sep, @quote_char)
65
71
  end
66
72
 
67
- # this can be called many times in order to append lines to the csv file
68
73
  def <<(data)
69
74
  case data
70
75
  when Hash
@@ -74,13 +79,15 @@ module SmarterCSV
74
79
  when NilClass
75
80
  # ignore
76
81
  else
82
+ # :nocov:
77
83
  raise InvalidInputData, "Invalid data type: #{data.class}. Must be a Hash or an Array."
84
+ # :nocov:
78
85
  end
79
86
  end
80
87
 
81
88
  def finalize
82
- # Map headers if :map_headers option is provided
83
89
  mapped_headers = @headers.map { |header| @map_headers[header] || header }
90
+ mapped_headers = mapped_headers.map { |x| escape_csv_field(x) } if @force_quotes
84
91
 
85
92
  @temp_file.rewind
86
93
  @output_file.write(mapped_headers.join(@col_sep) + @row_sep)
@@ -99,17 +106,43 @@ module SmarterCSV
99
106
  @headers.concat(new_keys)
100
107
  end
101
108
 
102
- # Reorder the hash to match the current headers order and fill missing fields
103
- ordered_row = @headers.map { |header| hash[header] || '' }
109
+ # Reorder the hash to match the current headers order and fill + map missing keys
110
+ ordered_row = @headers.map do |header|
111
+ has_header = hash.key?(header)
112
+ value = has_header ? hash[header] : '' # default to empty value
113
+
114
+ # first map individual keys
115
+ value = map_value(header, value) if @mapped_keys.include?(header)
116
+
117
+ # then apply general mapping rules
118
+ value = map_all_values(header, value) if @map_all_keys
119
+
120
+ escape_csv_field(value) # for backwards compatibility
121
+ end
104
122
 
105
- @temp_file.write ordered_row.map { |value| escape_csv_field(value) }.join(@col_sep) + @row_sep
123
+ @temp_file.write ordered_row.join(@col_sep) + @row_sep
124
+ end
125
+
126
+ def map_value(key, value)
127
+ @value_converters[key].call(value)
128
+ end
129
+
130
+ def map_all_values(key, value)
131
+ @value_converters[:_all].call(key, value)
106
132
  end
107
133
 
108
134
  def escape_csv_field(field)
109
- if @force_quotes || field.to_s.match(@quote_regex)
110
- "\"#{field}\""
135
+ str = field.to_s
136
+ return str if @disable_auto_quoting
137
+
138
+ # double-quote fields if we force that, or if the field contains the comma, new-line, or quote character
139
+ contains_special_char = str.to_s.match(@quote_regex)
140
+ if @force_quotes || contains_special_char
141
+ str = str.gsub(@quote_char, @quote_char * 2) if contains_special_char # escape double-quote
142
+
143
+ "\"#{str}\""
111
144
  else
112
- field.to_s
145
+ str
113
146
  end
114
147
  end
115
148
  end
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: smarter_csv
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.13.0
4
+ version: 1.14.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Tilo Sloboda
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2024-11-05 00:00:00.000000000 Z
11
+ date: 2025-04-07 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: awesome_print
@@ -117,7 +117,8 @@ files:
117
117
  - Rakefile
118
118
  - TO_DO_v2.md
119
119
  - docs/_introduction.md
120
- - docs/basic_api.md
120
+ - docs/basic_read_api.md
121
+ - docs/basic_write_api.md
121
122
  - docs/batch_processing.md
122
123
  - docs/data_transformations.md
123
124
  - docs/examples.md
@@ -165,7 +166,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
165
166
  - !ruby/object:Gem::Version
166
167
  version: '0'
167
168
  requirements: []
168
- rubygems_version: 3.2.3
169
+ rubygems_version: 3.5.4
169
170
  signing_key:
170
171
  specification_version: 4
171
172
  summary: Convenient CSV Reading and Writing