module Kakimasu module Generators class RestoreBackupGenerator < Rails::Generators::Base backup_file = '.kakimasu_backup.yml' # Checks if there is backup file unless File.file?(backup_file) puts '**************************' puts "Backup file can't be found" puts '**************************' else # Reads content of backup file backup_file_content = File.read(backup_file) locale = nil # Used to store locale for a temporary time key_parts = [] # Used to store parts of the 'lazy lookup' key, to at the end join them in one key lazy_lookup = false # Determines if key is lazy lookup # Read backup file by lines backup_file_content.each_line do |line| # Every line with translation starts with spaces if line.start_with?(' ') # Gets level of the key and gets translation # Check if it is first level key if line.match /^\s\s[\w]+[:]\s["][^"]+["]/ # Get translation key and translation from the line translation_key = line.scan(/^\s\s([\w]+)[:]\s["][^"]+["]/).first.first translation = line.scan(/^\s\s[\w]+[:]\s["]([^"]+)["]/).first.first # empty 'lazy lookup' key parts array because this means that lazy lookup key is done even if there was no translation (That means it has no translation) key_parts = [] lazy_lookup = false # If its not first level translation, then it means that this is 'lazy lookup' translation else lazy_lookup = true # If line has no translation, just key, then it is part of 'lazy lookup' key if line.match /\w+[:]$/ key_parts.push line.scan(/(\w+)[:]$/).first.first # Gets 'lazy lookup' key part from the line and pushes it into array # If key has translation then it is last part of 'lazy lookup' key elsif line.match /\w+[:]\s["]([^"]+)["]/ # Gets 'lazy lookup' keys last part and gets translation key_parts.push line.scan(/(\w+)[:]\s["][^"]+["]/).first.first translation = line.scan(/\w+[:]\s["]([^"]+)["]/).first.first end end # lines with no spaces in start is just for locales or blank lines else # If line is not meant as blank line, then it's locale and function gets locale from it locale = line.partition(':').first unless line.start_with?("\n") end # If 'lazy lookup' key then save it as 'lazy lookup' key otherwise save it like not 'lazy lookup key' if lazy_lookup && translation # Form 'lazy lookup' key translation_key = key_parts.join('.') # Store translation I18n.backend.store_translations(locale, {translation_key => translation}, escape: false) # Set back variables key_parts = [] translation = nil translation_key = nil elsif translation_key && translation # Store translation I18n.backend.store_translations(locale, {translation_key => translation}, escape: false) # Set back variables translation = nil translation_key = nil end end # Message about successfull translation restore from backup file puts '***********************************' puts 'Translations successfully restored!' puts '***********************************' end end end end