在ActionMailer中,我试图将数组的数组转换为CSV,并确保可以读取该文件,就像在使用BOM的UTF8中将其转换一样。
以前,我将内容复制到Sublime Text中的新文件中,然后单击File > Save With Encoding > UTF8 with BOM
,否则字符最终会弄乱。
在通过ActionMailer发送内存中CSV时如何实现相同的编码(我从未将文件写入磁盘)
这是我发送电子邮件的示例代码
class CSVMailer < ApplicationMailer
def csv(csv_as_array_of_array,
to:,
cc: [],
from: 'messages-noreply@example.com',
reply_to: 'me@example.com',
subject: 'Here is your CSV made with love ',
filename: 'your_csv_made_with_love.csv'
)
attach_csv(csv_as_array_of_array, filename: filename)
mail(
to: to,
cc: cc,
subject: subject
)
end
private
def attach_csv(array_of_arrays, filename:)
attachments[filename] = {
mine_type: 'text/csv',
content: CSV.generate(col_sep: ';') do |csv|
array_of_arrays.each do |row|
csv << row
end
end
}
end
end
答案 0 :(得分:0)
好的,这是我的方法,假设您要将以下数组数组发送给mailer函数
csv_as_array_of_array = [
['header1', 'header2'],
['row1cell1', 'row1cell2'],
...
]
将utf8 bom附加到csv的简单实用函数就足够了
# Small utility method
def Utility.with_utf8_bom(content)
"\uFEFF" + content
end
因此在ActionMailer类中
class CSVMailer < ApplicationMailer
# app/mailers/csv_mailer.rb
def send_email_with_csv(csv_as_array_of_array)
...
attach_csv(csv_as_array_of_array, filename: filename)
mail(to: ...)
end
private
def attach_csv(array_of_arrays, filename:)
attachments[filename] = {
mine_type: 'text/csv',
content: Utility.with_utf8_bom(
CSV.generate(col_sep: ';', encoding: Encoding::UTF_8) do |csv|
array_of_arrays.each do |row|
csv << row
end
end
)
}
end