Mysql Ruby CSV:如何将nil字段写入为\N
我想用ruby的默认CSV库编写一个CSV,以便使用MySQL的快速导入加载数据填充 当前,当我为字段输入nil时,它被写为Mysql Ruby CSV:如何将nil字段写入为\N,mysql,ruby,csv,Mysql,Ruby,Csv,我想用ruby的默认CSV库编写一个CSV,以便使用MySQL的快速导入加载数据填充 当前,当我为字段输入nil时,它被写为,我希望它是\N、 (大写N表示空,不要与换行符混淆) CSV.open(产品更新文件名,wb,{col\u sep:;”,标题:false,强制引用:false})do |产品CSV| product_csv尝试将nil的重写为\u s方法,如下所示: class << nil def to_s "my nil placeholder text"
代码>,我希望它是\N、 代码>(大写N表示空,不要与换行符混淆)
CSV.open(产品更新文件名,wb,{col\u sep:;”,标题:false,强制引用:false})do |产品CSV|
product_csv尝试将nil
的重写为\u s
方法,如下所示:
class << nil
def to_s
"my nil placeholder text"
end
end
class您可以修改CSV方法:
require 'csv'
class Array
alias :old_to_csv :to_csv
#Extend to_csv for usage like ["foo", nil, "bar"].to_csv( :col_sep => ";")
def to_csv(options)
self.map{|s| s.nil? ? '\N' : s }.old_to_csv
end
end
class CSV
alias :old_push :<<
def <<(data)
case data
when Array
old_push data.map{|s| s.nil? ? '\N' : s }
else
old_push data
end
end
end
#Testcode:
puts ["foo", nil, "bar"].to_csv( :col_sep => ";") #--> [["foo", "\\N", "bar"]]
CSV.open('test.csv', "wb",
{col_sep: ";", headers: false, force_quotes: false }
) do |product_csv|
product_csv << ["foo", nil, "bar"]
end
#-> Creates test.csv with 'foo;\N;bar'
也许其他人知道一种使用转换器构建csv文件的方法。它是大型rails应用程序的一部分,所以我更喜欢一种更本地化的解决方案。尽管如此,还是要谢谢你。我一开始也试着使用转换器,但无法运行。我会试试你的其他解决方案,谢谢。
require 'csv'
class Array
alias :old_to_csv :to_csv
#Extend to_csv for usage like ["foo", nil, "bar"].to_csv( :col_sep => ";")
def to_csv(options)
self.map{|s| s.nil? ? '\N' : s }.old_to_csv
end
end
class CSV
alias :old_push :<<
def <<(data)
case data
when Array
old_push data.map{|s| s.nil? ? '\N' : s }
else
old_push data
end
end
end
#Testcode:
puts ["foo", nil, "bar"].to_csv( :col_sep => ";") #--> [["foo", "\\N", "bar"]]
CSV.open('test.csv', "wb",
{col_sep: ";", headers: false, force_quotes: false }
) do |product_csv|
product_csv << ["foo", nil, "bar"]
end
#-> Creates test.csv with 'foo;\N;bar'
CSV::Converters[:nil_N] = lambda{|s|
s.nil? ? '\N' : s
}
p CSV.parse('foo;;bar', :col_sep => ";", :converters => :nil_N)
#-> [["foo", "\\N", "bar"]]