Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/64.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Ruby/Rails:CSV特定于列的转换器_Ruby On Rails_Ruby_Csv - Fatal编程技术网

Ruby on rails Ruby/Rails:CSV特定于列的转换器

Ruby on rails Ruby/Rails:CSV特定于列的转换器,ruby-on-rails,ruby,csv,Ruby On Rails,Ruby,Csv,我有一个CSV,使用默认的CSV库希望对不同的列应用不同的转换器 标题为: units_at_warehouse(#integer), external_id(#string), released(#date), list_price_cents(#integer) 我目前正在使用这些选项: options = { headers: true, converters: nil, header_converters: :symbol } CSV.fore

我有一个CSV,使用默认的CSV库希望对不同的列应用不同的转换器

标题为:

units_at_warehouse(#integer),
  external_id(#string),
    released(#date),
      list_price_cents(#integer)
我目前正在使用这些选项:

options = {
  headers: true, 
  converters: nil, 
  header_converters: :symbol
}

CSV.foreach(file, options) do |row|
  # current my best option is:
  convert_integers(row)
  convert_dates(row)
  persist(row)#...saving
end
是否可以为每个列传入转换器

比如:

options = {
  headers: true, 
  header_converters: :symbol,
  converters: {
    units_at_warehouse: :numeric,
    list_price_cents: :numeric,
    released: :date
  }
}

虽然CSV不提供这样的接口,但它允许您指定多个转换器进行尝试。它仅在值与该筛选器的预期格式匹配时应用每个筛选器

因此,您可以在选项中指定这两个转换器,只要列的值与整数或日期的格式匹配,CSV就会智能地应用它们

converters: [:integer, :date]
这种方法的缺点是,它还将转换其他列中的日期和整数,而不是将它们保留为字符串

如果需要绕过此限制,可以提供一个lambda转换器,该转换器接受两个参数,其中第二个参数是包含标题的
CSV::FieldInfo
,即值所在的列,并仅将转换应用于特定列