SaneCsv
This ensures that the CSV
never returns nil
when parsing.
Additionally, empty strings will not be quoted when generating CSV.
Installation
Install the gem and add to the application's Gemfile by executing:
$ bundle add sane_csv
If bundler is not being used to manage dependencies, install the gem by executing:
$ gem install sane_csv
Usage
require 'sane_csv'
CSV
may return nil
, but using SaneCsv
ensures it never returns nil
.
The default behavior of CSV
:
require 'csv'
CSV.parse('a,,b')[0]
#=> ["a", nil, "b"]
To avoid returning nil
, you need to specify the nil_value
option:
require 'csv'
CSV.parse('a,,b', nil_value: "")[0]
#=> ["a", "", "b"]
When using SaneCsv
:
require 'sane_csv'
CSV.parse('a,,b')[0]
#=> ["a", "", "b"]
If you have a special situation where you want to return nil
, you can specify the nil_value
option:
require 'sane_csv'
CSV.parse('a,,b', nil_value: nil)[0]
#=> ["a", nil, "b"]
Additionally, when generating CSV
, empty strings are not unnecessarily quoted:
require 'sane_csv'
['a', '', 'b'].to_csv
#=> "a,,b\n"
If you have a specific reason to quote empty strings, you can specify quote_empty
:
require 'sane_csv'
['a', '', 'b'].to_csv(quote_empty: true)
#=> "a,\"\",b\n"