tilo/smarter_csv

Example of custom Procs for hash_transformations in 2.0 documentation

creativetags opened this issue · 2 comments

Could we have an example of how to implement a custom Proc for a hash_transformations say on this page: https://github.com/tilo/smarter_csv/wiki/Hash-Transformations

There is one on the header_transformations page but it doesn't seem to work the same way for hash_transformations

My guess didn't work:

filter_posts = Proc.new {|hash, args=nil|
      keys = (args.nil? || args.empty?) ? hash.keys : ( args.is_a?(Array) ? args : [ args ] )
      # this is just taken from strip_spaces 
      keys.each {|key| hash[key].strip! unless hash[key].nil? }
      hash
    }
}

options = {
  hash_transformations: [ filter_posts, :strip_spaces, :remove_blank_values ]
}
data = SmarterCSV.process('/tmp/test.csv', options)
 => [{"Category"=>"Red", "FirstName"=>"John", "Age"=>"35"}]

In answer to my own question, here's an example for date formatting:

filter_posts = Proc.new {|hash|
  hash[:date] = Date.strptime(hash[:date], "%d/%m/%y") if hash[:date].is_a?(String)
  # Need to return the hash
  hash
}

options = {
  hash_transformations: [ filter_posts ]
}
data = SmarterCSV.process('/tmp/test.csv', options)
tilo commented

Ear-marked for v2.0