Ruby,Tempfile,CSV

时间:2013-01-28 22:19:29

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

我有以下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

1 个答案:

答案 0 :(得分:0)

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

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

我们称之为类方法和实例方法。