Rails-使用ActionMailer中的BOM附加可读取为UTF8格式的CSV文件

时间:2018-09-07 16:55:31

标签: ruby-on-rails csv encoding actionmailer

在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

1 个答案:

答案 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