Skip to content

Header Transformations

Tilo edited this page Feb 13, 2022 · 3 revisions

Pre-Defined Header Transformations

:none

to disable any pre-existing default settings, so you can start from a clean-slate.

:keys_as_symbols

This is the default behavior, as explained in The Basics.

:keys_as_strings

Similar, but strings. Also explained in The Basics.

Don't forget to start with :none.

:key_mapping

With :key_mapping you can completely or partially re-map your header keys.

Maps keys from -> to, and can map headers to nil, so they can be omitted from the result hashes.

The key_mapping_spec.rb has some examples on how to use this.

Custom Header Transformations via Procs

You can always define your own custom Procs.

camelcase_headers = Proc.new {|headers|
  headers.map{|x| x.strip.downcase.gsub(/(\s|\-)+/,'_').split('_').map(&:capitalize).join }
}

options = {
  header_transformations: [:none, camelcase_headers ]
}
data = SmarterCSV.process('/tmp/test.csv', options)
 => [{"Category"=>"Red", "FirstName"=>"John", "Age"=>"35"}]