71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
|
# File 'app/models/rails_i18n_manager/translation_key.rb', line 71
def self.export_to(app_name: nil, zip: false, format: :yaml)
format = format.to_sym
if format == :yaml
format = "yml"
elsif [:yaml, :json].exclude?(format)
raise ArgumentError.new("Invalid format provided")
end
base_export_path = Rails.root.join("tmp/export/translations/")
files_to_delete = Dir.glob("#{base_export_path}/*").select{|f| File.ctime(f) < 1.minutes.ago }
if !files_to_delete.empty?
FileUtils.rm_r(files_to_delete, force: true)
end
base_folder_path = File.join(base_export_path, "#{Time.now.to_i}-#{SecureRandom.hex(6)}/")
FileUtils.mkdir_p(base_folder_path)
if app_name.nil?
translation_apps = TranslationApp.order(name: :asc)
else
translation_apps = [TranslationApp.find_by!(name: app_name)]
end
if translation_apps.empty?
return nil
end
translation_apps.each do |app_record|
current_app_name = app_record.name
key_records = app_record.translation_keys.order(key: :asc).includes(:translation_values)
app_record.all_locales.each do |locale|
tree = {}
key_records.each do |key_record|
val_record = key_record.translation_values.detect{|x| x.locale == locale.to_s}
split_keys = [locale.to_s] + key_record.key.split(".")
RailsI18nManager.hash_deep_set(tree, split_keys, val_record.try!(:translation))
end
filename = File.join(base_folder_path, current_app_name, "#{locale}.#{format}")
FileUtils.mkdir_p(File.dirname(filename))
File.open(filename, "wb") do |io|
if format == :json
str = tree.to_json
else
str = tree.to_yaml(line_width: -1).sub("---\n", "")
end
io.write(str)
end
end
end
if zip
temp_file = Tempfile.new([Time.now.to_i.to_s, ".zip"], binmode: true)
files_to_write = Dir.glob("#{base_folder_path}/**/**")
if files_to_write.empty?
return nil
end
zip_file = Zip::File.open(temp_file, create: !File.exist?(temp_file)) do |zipfile|
files_to_write.each do |file|
zipfile.add(file.sub(base_folder_path, "translations/"), file)
end
end
output_path = temp_file.path
elsif app_name
output_path = File.join(base_folder_path, app_name)
else
output_path = base_folder_path
end
return output_path
end
|