Class: I18nContextGenerator::Writers::StringsWriter
- Inherits:
-
Object
- Object
- I18nContextGenerator::Writers::StringsWriter
- Includes:
- Helpers
- Defined in:
- lib/i18n_context_generator/writers/strings_writer.rb
Overview
Writer that updates iOS .strings files with context comments Uses the dotstrings gem for proper parsing and generation
Instance Method Summary collapse
-
#initialize(context_prefix: 'Context: ', context_mode: 'replace') ⇒ StringsWriter
constructor
A new instance of StringsWriter.
- #write(results, source_path) ⇒ Object
Methods included from Helpers
#find_swift_files, #result_matches_source_path?, #skip_description?, #writable_result?
Constructor Details
#initialize(context_prefix: 'Context: ', context_mode: 'replace') ⇒ StringsWriter
Returns a new instance of StringsWriter.
12 13 14 15 |
# File 'lib/i18n_context_generator/writers/strings_writer.rb', line 12 def initialize(context_prefix: 'Context: ', context_mode: 'replace') @context_prefix = context_prefix @context_mode = context_mode end |
Instance Method Details
#write(results, source_path) ⇒ Object
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 56 57 |
# File 'lib/i18n_context_generator/writers/strings_writer.rb', line 17 def write(results, source_path) return unless File.exist?(source_path) original_content = File.binread(source_path) # Parse the existing file original_file = DotStrings.parse_file(source_path, strict: false) results_by_key = results.each_with_object({}) do |result, lookup| next unless result_matches_source_path?(result, source_path) lookup[result.key] = result end return false unless results_by_key.values.any? { |result| writable_result?(result) } # Build new file with updated comments (DotStrings::Item is immutable) new_file = DotStrings::File.new original_file.items.each do |item| result = results_by_key[item.key] new_comment = if writable_result?(result) build_comment(item.comment, result.description) else item.comment end new_item = DotStrings::Item.new( key: item.key, value: item.value, comment: new_comment ) new_file << new_item end rendered = new_file.to_s return false if rendered == original_content AtomicFile.replace(source_path, rendered) do |candidate_path| DotStrings.parse_file(candidate_path, strict: true) end true end |