【问题标题】:Ruby, Tempfile, CSV红宝石、临时文件、CSV
【发布时间】:2013-01-28 22:19:29
【问题描述】:

我有下面的 resque 作业,它生成一个 csv 文件并将其发送到邮件程序。我想验证 csv 文件是否有数据,所以我不会通过电子邮件发送空白文件。出于某种原因,当我在 perform 方法之外编写方法时,它将不起作用。例如,当我知道 csv 文件的第一行有数据时,下面的代码将打印无效。如果我取消注释下面的行,确保它正常工作,但是我想将这个文件检查提取到一个单独的方法中。这是正确的吗?

class ReportJob
  @queue = :report_job

def self.perform(application_id, current_user_id)
 user = User.find(current_user_id)
 client_application = Application.find(client_application_id)
 transactions = application.transactions
 file = Tempfile.open(["#{Rails.root}/tmp/", ".csv"]) do |csv|
   begin
     csv_file = CSV.new(csv)
     csv_file << ["Application", "Price", "Tax"]
     transactions.each do |transaction|
       csv_file << [application.name, transaction.price, transaction.tax]
     end
   ensure
    ReportJob.email_report(user.email, csv_file)
    #ReportMailer.send_report(user.email, csv_file).deliver
     csv_file.close(unlink=true)
   end
 end
end

 def self.email_report(email, csv)
   array = csv.to_a
   if array[1].blank?
     puts "invalid"
   else
     ReportMailer.send_report(email, csv).deliver
   end
 end

end

【问题讨论】:

    标签: ruby-on-rails ruby csv temporary-files


    【解决方案1】:

    你应该这样调用你的方法:

    ReportJob.email_report(email, csv)
    

    否则,去掉self in:

    def self.email_report(email, csv)
       # your implementation here.
    end 
    

    并按如下方式定义您的方法:

    def email_report(email, csv)
      # your implementation.
    end
    

    这就是我们所说的类方法和实例方法。

    【讨论】:

    • 谢谢-我尝试按照您所说的那样调用它,似乎该块在该方法有机会通过文件之前完成。我想知道这是否与 tempfile 类有关?
    猜你喜欢
    • 2014-02-22
    • 1970-01-01
    • 2017-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-02
    • 2019-08-09
    • 1970-01-01
    相关资源
    最近更新 更多