-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathcontext_formatter.rb
55 lines (44 loc) · 1.9 KB
/
context_formatter.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
module Poesie
module ContextFormatter
# Write the JSON output file containing all context keys
#
# @param [Array<Hash<String, Any>>] terms
# JSON returned by the POEditor API
# @param [String] file
# The path of the file to write
# @param [Regexp] exclude
# A regular expression to filter out terms.
# Terms matching this Regexp will be ignored and won't be part of the generated file
#
def self.write_context_json(terms, file, exclude: nil)
json_hash = { "date" => "#{Time.now}" }
stats = { :excluded => 0, :nil => 0, :count => 0 }
#switch on term / context
array_context = Array.new
terms.each do |term|
(term, definition, comment, context) = ['term', 'definition', 'comment', 'context'].map { |k| term[k] }
# Filter terms and update stats
next if (term.nil? || term.empty? || context.nil? || context.empty?) && stats[:nil] += 1
next if (term =~ exclude) && stats[:excluded] += 1 # Remove android-specific strings
stats[:count] += 1
# Escape some chars
context = context
.gsub("\u2028", '') # Sometimes inserted by the POEditor exporter
.gsub("\\", "\\\\\\") # Replace actual \ with \\
.gsub('\\\\"', '\\"') # Replace actual \\" with \"
.gsub(/%(\d+\$)?s/, '%\1@') # replace %s with %@ for iOS
array_context << { "term" => "#{term}", "context" => "#{context}" }
end
json_hash[:"contexts"] = array_context
context_json = JSON.pretty_generate(json_hash)
Log::info(" - Save to file: #{file}")
File.open(file, "w") do |fh|
fh.write(context_json)
end
Log::info(" [Stats] #{stats[:count]} strings processed")
unless exclude.nil?
Log::info(" Filtered out #{stats[:excluded]} strings matching #{exclude.inspect})")
end
end
end
end