Rails - 压缩CSV文件

时间:2018-02-09 15:36:17

标签: ruby-on-rails ruby compression

我正在尝试将压缩的CSV文件附加到电子邮件中,没有任何乐趣。我试过跟http://api.rubyonrails.org/classes/ActiveSupport/Gzip.html

class UserExportProcessor

 @queue = :user_export_queue

  def self.perform(person_id, collection_ids)
    person = Person.unscoped.find(person_id)
    collection = Person.unscoped.where(id: [49522, 70789])
    file = ActiveSupport::Gzip.compress(collection.to_csv)
    PersonMailer.people_export(person, file).deliver
  end
end

这会发送一个附件 - 仍然是一个CSV文件 - 填充符号(没有字母或数字)。

当我尝试删除压缩时:

class UserExportProcessor

 @queue = :user_export_queue

  def self.perform(person_id, collection_ids)
    person = Person.unscoped.find(person_id)
    collection = Person.unscoped.where(id: [49522, 70789])
    PersonMailer.people_export(person, collection.to_csv).deliver
  end
end

系统按原样通过电子邮件发送CSV文件,并正确形成CSV。我究竟做错了什么?我是否需要从压缩数据中创建新文件?我尝试了各种各样的方法,但没有快乐。

提前致谢

编辑:我正在尝试

class UserExportProcessor
  require 'zip'

  @queue = :user_export_queue

  def self.perform(person_id, collection_ids)
    person = Person.unscoped.find(person_id)
    collection = Person.unscoped.where(id: [49522, 70789])
    file = Zip::ZipFile.open("files.zip", Zip::ZipFile::CREATE) { |zipfile|
      puts zipfile.get_output_stream(collection.to_csv)
      zipfile.mkdir("a_dir")
    end
    PersonMailer.people_export(person, file).deliver
  end
end

然而,这失败了:

Errno::ENAMETOOLONG: File name too long - /Users/mark/projects/bla/Role,Title,First Name,Last Name,Address 1,Address 2,Address 3,City,Postcode,Country,Email,Telephone,Mobile,Job Title,Company,Area of work,Department,Regions,Account Manager,Sales Coordinator,Production Studios,Production Partners,Genres,Last login,Created date

我有什么方法可以用上面的方法设置文件名吗?

1 个答案:

答案 0 :(得分:1)

错误可能发生在PersonMailer.people_export的代码中(您没有包含)。所以这是我最好的猜测:您可能添加附件并且没有正确定义mime类型。

确保在添加附件时设置正确的文件扩展名:

http://edgeguides.rubyonrails.org/action_mailer_basics.html#adding-attachments

沿着这条线的东西应该有效:

attachments['archive.zip'] = ActiveSupport::Gzip.compress(collection.to_csv)