survey/lib/tasks/survey_tasks.rake

34 lines
1.2 KiB
Ruby

# desc "Explaining what the task does"
# task :survey do
# # Task goes here
# end
namespace :survey_tasks do
task :prepare_download,[:surveyid] => :environment do |task,args|
puts "Cron initiated with #{args.surveyid}"
id = args.surveyid
I18n.locale = :zh_tw
survey = QuestionnaireSurvey.find(id)
chart_data, survey_questions, survey_answers = survey.generate_chart_data
ac = ActionController::Base.new()
xlsx = ac.render_to_string handlers: [:axlsx], formats: [:xlsx], template: "survey_export/export", locals: {survey: survey, survey_questions: survey_questions, survey_answers: survey_answers}
dirname = "public/uploads/survey_export/#{id}"
FileUtils.mkdir_p(dirname) unless File.exists?(dirname)
f = "#{dirname}/#{survey.title.gsub(/[ "'*@#$%^&()+=;:.,?>|\\\/<~_!:,、。!?;「」〈〉【】/]/,'')}.xlsx"
if File.exists?(f)
File.delete(f)
end
file = File.open(f, "w")
xlsx.force_encoding("utf-8")
file.write(xlsx)
end
end
def remove_illegal_utf8(str)
if String.method_defined?(:encode)
str.encode!('UTF-8', 'UTF-8', :invalid => :replace)
else
ic = Iconv.new('UTF-8', 'UTF-8//IGNORE')
str = ic.iconv(str)
end
str
end