survey/lib/tasks/survey_tasks.rake

34 lines
1.2 KiB
Ruby
Raw Normal View History

2014-10-06 05:55:25 +00:00
# desc "Explaining what the task does"
# task :survey do
# # Task goes here
# end
2017-04-11 06:10:01 +00:00
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}
2017-04-11 10:43:22 +00:00
dirname = "public/uploads/survey_export/#{id}"
2017-04-11 06:10:01 +00:00
FileUtils.mkdir_p(dirname) unless File.exists?(dirname)
2017-04-11 10:43:22 +00:00
f = "#{dirname}/#{survey.title.gsub(/[ "'*@#$%^&()+=;:.,?>|\\\/<~_!:,、。!?;「」〈〉【】/]/,'')}.xlsx"
2017-04-11 06:10:01 +00:00
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