require 'csv' require 'nokogiri' module MultiLangTrans class << self INPUT_FOLDER = 'input/*.csv' TEMPLATE_FOLDER = 'template/*.resw' TEMPLATE_CSV_PATH = 'template/template.csv' def run template_file_paths = Dir.glob(TEMPLATE_FOLDER) print "Using #{template_file_paths.first}, " make_template(template_file_paths.first) input_file_paths = Dir.glob(INPUT_FOLDER) puts "#{input_file_paths.count} file(s) translating..." input_file_paths.each do |input_file_path| input_content = read_csv(input_file_path) output_file_paths = get_output_paths(input_file_path) print " * #{input_file_path} --> #{output_file_paths[:matched]}, #{output_file_paths[:dismatched]}: " puts 'ok!' if write_xml(output_file_paths, input_content) end puts 'Done!' end private def make_template(template_file_path) xml_doc = File.open(template_file_path) { |f| Nokogiri::XML(f) } File.open(TEMPLATE_CSV_PATH, 'w') do |f| f.puts("name,trans_value,trans_comment") xml_doc.xpath("//data").each do |data| value = data.at_xpath('value').content unless data.at_xpath('value').nil? comment = data.at_xpath('comment').content unless data.at_xpath('comment').nil? f.puts("#{data['name']},#{value},#{comment}") end end @template_content = read_csv(TEMPLATE_CSV_PATH) end def read_csv(csv_file_path) input_content = [] CSV.foreach(csv_file_path, headers: true) do |row| input_content << row.to_hash end input_content end def get_output_paths(input_path) output_paths = {} output_path = input_path.sub('input/', "output/") output_paths[:matched] = output_path.sub('.csv', ".txt") output_paths[:dismatched] = output_path.sub('.csv', "-not-found.txt") output_paths end def write_xml(xml_file_paths, content_rows) not_found_rows = [] File.open(xml_file_paths[:matched], 'w') do |f| content_rows.each_with_index do |row, index| template_row = @template_content.find{|t| t['trans_value'] == row['template_value']} if template_row.nil? not_found_rows << "line:#{index + 2}.\t#{row['template_value']}" else f.puts("") f.puts(" #{template_row['trans_value']}") unless template_row['trans_value'].nil? f.puts(" #{row['trans_value']}") unless row['trans_value'].nil? f.puts(" #{template_row['trans_comment']}") unless template_row['trans_comment'].nil? f.puts("") end end end File.open(xml_file_paths[:dismatched], 'w') do |f| not_found_rows.each { |row| f.puts(row) } end true rescue => e puts e false end end end MultiLangTrans.run