module Aigu class Importer ARRAY_REGEX = /___KEY___(?\d+)$/ def initialize(input_file: nil, output_directory: nil, locale: nil) @input_file = input_file @output_directory = output_directory @locale = locale end def process! puts "Generating YAML files in `#{@output_directory}` based on Accent-generated `#{@input_file}` file" puts '---' parse_json build_blob write_yaml_files puts '---' puts 'Done' end protected def parse_json json = File.read(@input_file) @object = JSON.parse(json) @object = expand_content_values(@object) @object = localize_content_keys(@object) end def write_yaml_files @blob.each_pair do |file_name, hash| file_path = File.join(@output_directory, "#{file_name}.yml") puts "Generating #{file_path}" FileUtils.mkdir_p(File.dirname(file_path)) File.open(file_path, 'w+') do |file| file << hash.to_yaml(line_width: 100_000_000) end end end def build_blob @blob = Hash.recursive @object.each_pair do |key, value| filename, flat_key = key.split('|') parts = flat_key.split('.') hash = @blob[filename] parts.each_with_index do |part, index| if index + 1 < parts.length hash = hash[part] else hash[part] = value end end end end def localize_content_keys(content) content.reduce({}) do |memo, (key, value)| localized_key = key.gsub(/^([^|]+)\|/, "\\1.#{@locale}|#{@locale}.") memo.merge localized_key => value end end def expand_content_values(content) content.reduce({}) do |memo, (key, value)| match_data = key.match(ARRAY_REGEX) if match_data canonical_key = key.gsub(ARRAY_REGEX, '') value_index = match_data[:index].to_i memo[canonical_key] ||= [] memo[canonical_key][value_index] = sanitize_string_to_value(value) else memo[key] = sanitize_string_to_value(value) end memo end end def sanitize_string_to_value(string) case string when '___TRUE___' true when '___FALSE___' false when '___NULL___' nil else string end end end end