You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
educoder/app/services/batch_export_shixun_report_...

60 lines
1.5 KiB

class BatchExportShixunReportService
Error = Class.new(StandardError)
MAX_BATCH_LIMIT = 20
# attr_reader :homework, :student_work_ids
attr_reader :homework, :all_student_works
def initialize(homework, all_student_works)
@homework = homework
# @student_work_ids = student_work_ids
@all_student_works = all_student_works
end
def filename
@_filename ||= "#{Time.now.strftime('%Y%m%d%H%M%S')}-#{homework.name}.zip"
end
def zip
# validate!
student_works = all_student_works.includes(:myshixun, user: :user_extension)
if student_works.count.zero?
raise Error, '请选择要导出的学生实训报告'
end
pdfs = []
zip_file = Tempfile.new(filename)
Zip::File.open(zip_file.path, Zip::File::CREATE) do |zip|
student_works.find_each.map do |student_work|
export = ExportShixunReportService.new(homework, student_work)
pdf = export.to_pdf
pdfs << pdf
begin
zip.add(export.filename, pdf.path)
rescue => ex
Rails.logger.error(ex.message)
zip.get_output_stream('FILE_NOTICE.txt'){|os| os.write('文件重复') }
next
end
end
zip_file
end
end
# private
#
# def validate!
# if student_work_ids.size.zero?
# raise Error, '请选择学生实训作业'
# end
#
# if student_work_ids.size > MAX_BATCH_LIMIT
# raise Error, '导出实训报告太多,请分批导出'
# end
# end
end