Module: Poesie::ContextFormatter

Defined in:
lib/context_formatter.rb

Class Method Summary collapse

Class Method Details

.write_context_json(terms, file, exclude: nil) ⇒ Object

Write the JSON output file containing all context keys

Parameters:

  • terms (Array<Hash<String, Any>>)

    JSON returned by the POEditor API

  • file (String)

    The path of the file to write

  • exclude (Regexp) (defaults to: nil)

    A regular expression to filter out terms. Terms matching this Regexp will be ignored and won’t be part of the generated file



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
# File 'lib/context_formatter.rb', line 14

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