gpt4 book ai didi

ruby-on-rails - CSV 文件中有随机的新行/拆分。为什么会这样?

转载 作者:太空宇宙 更新时间:2023-11-03 16:46:26 25 4
gpt4 key购买 nike

我正在使用 Rails 并每周生成一封 CSV 电子邮件。

module CSVData
class Report
HEADER = ["url", "description", "title", "logo_url", "created_at"]

attr_reader :start_date, :end_date, :file_name, :posts

def initialize(time)
@start_date = time - 7.days
@end_date = time
@file_name = "post_data_#{@end_date.strftime("%-m_%-d_%Y")}"
@posts = Post.where(created_at: @start_date..@end_date)
end

def create_csv
file = File.new(File.join(Dir.pwd, "/tmp/#{@file_name}.csv"), "w+")
CSV.open(file, "wb") { |csv| write_data(csv) }
file
end

def write_data(csv)
csv << HEADER
@posts.each do |post|
csv << data_row(post)
end
csv
end

def data_row(post)
description = post.description || ""
description = "\"" + description.gsub("\"", "\"\"") + "\""
description = description.squish

["http://#{ENV['HOST']}/#{post.slug}",
description,
post.title,
"http://#{ENV['HOST']}#{post.author.logo.url(:thumb)}",
post.created_at.strftime("%m/%d/%Y %H:%M")]
end
end
end

邮寄者

  def post_data_email
time = Time.now
@file = CSVData::Report.new(time).create_csv
attachments["Post_Data_#{time.strftime("%m_%d_%Y")}.csv"] = {
:content => @file.read
}

## Mail details
end

当我在开发中运行它时,它运行良好,CSV 文件也很好。然而,生产中的自动化(带有“每当 gem”)电子邮件有一些奇怪的错误,其中数据被拆分到换行符上。通常在“url”、“description”或“logo_url”中

有时在描述的中间它会跳到一个新行

http://...,"""Here is a description that will be fine and then just 

jump to a new line.""",Post Title,http://...thumb.jpg?1,08/14/2015 16:27

这个跳到logo_url中间

"Everything fine until here",http://example.com/logos/1441/thumb.png?143

9262835,08/11/2015 10:17

一行开头缺少“ht”。

tp://example.com/post,## the rest of the line is fine

这让我很困惑。知道什么可能导致这样的事情吗?

编辑:我已根据评论进行了更改,但仍然出现相同的错误。 Here is an image.

邮寄者

  def post_data_email
time = Time.now
@file = CSVData::Report.new(time).create_csv
attachments["Post_Data_#{time.strftime("%m_%d_%Y")}.csv"] = {
:content => File.read(@file.path)
}

## Mail details
end

create_csv 和 write_data 方法已更改

def create_csv
csv_string = CSV.generate(write_headers: true, headers: HEADER) { |csv| write_data(csv) }
file = File.new(File.join(Dir.pwd, "/tmp/#{@file_name}.csv"), "w+")
file.write(csv_string)
file.close
file
end

def write_data(csv)
@posts.each do |post|
csv << data_row(post)
end
csv
end

最佳答案

根据 RFC 821: SMTP , 电子邮件附件在 1000 个字符处被截断。

text line

The maximum total length of a text line including the is 1000 characters (but not counting the leadingdot duplicated for transparency).

解决方案是将附件编码为 base64:

attachments["Post_Data_#{time.strftime("%m_%d_%Y")}.csv"] = {
:data=> ActiveSupport::Base64.encode64(File.read(@file.path)),
:encoding => 'base64'
}

无耻地复制自How to send a csv attachment with lines longer than 990 characters?

关于ruby-on-rails - CSV 文件中有随机的新行/拆分。为什么会这样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32064859/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com