class I18n::JS::Segment

Class which enscapulates a translations hash and outputs a single JSON translation file

Constants

LOCALE_INTERPOLATOR
OPTIONS

Public Class Methods

new(file, translations, options = {}) click to toggle source
# File lib/i18n/js/segment.rb, line 15
def initialize(file, translations, options = {})
  @file         = file
  # `#slice` will be used
  # But when activesupport is absent,
  # the core extension from `i18n` gem will be used instead
  # And it's causing errors (at least in test)
  #
  # So the input is wrapped by our class for better `#slice`
  @translations = Private::HashWithSymbolKeys.new(translations)
  @namespace    = options[:namespace] || 'I18n'
  @pretty_print = !!options[:pretty_print]
  @js_extend    = options.key?(:js_extend) ? !!options[:js_extend] : true
  @prefix       = options.key?(:prefix) ? options[:prefix] : nil
  @suffix       = options.key?(:suffix) ? options[:suffix] : nil
  @sort_translation_keys = options.key?(:sort_translation_keys) ? !!options[:sort_translation_keys] : true
  @json_only = options.key?(:json_only) ? !!options[:json_only] : false
end

Public Instance Methods

save!() click to toggle source

Saves JSON file containing translations

# File lib/i18n/js/segment.rb, line 34
def save!
  if @file =~ LOCALE_INTERPOLATOR
    I18n::JS.js_available_locales.each do |locale|
      write_file(file_for_locale(locale), @translations.slice(locale))
    end
  else
    write_file
  end
end

Protected Instance Methods

file_for_locale(locale) click to toggle source
# File lib/i18n/js/segment.rb, line 46
def file_for_locale(locale)
  @file.gsub(LOCALE_INTERPOLATOR, locale.to_s)
end
formatter() click to toggle source
# File lib/i18n/js/segment.rb, line 63
def formatter
  if @json_only
    Formatters::JSON.new(**formatter_options)
  else
    Formatters::JS.new(**formatter_options)
  end
end
formatter_options() click to toggle source
# File lib/i18n/js/segment.rb, line 71
def formatter_options
  { js_extend: @js_extend,
    namespace: @namespace,
    pretty_print: @pretty_print,
    prefix: @prefix,
    suffix: @suffix
  }
end
write_file(_file = @file, _translations = @translations) click to toggle source
# File lib/i18n/js/segment.rb, line 50
def write_file(_file = @file, _translations = @translations)
  FileUtils.mkdir_p File.dirname(_file)
  _translations = Utils.deep_key_sort(_translations) if @sort_translation_keys
  _translations = Utils.deep_remove_procs(_translations)
  contents = formatter.format(_translations)

  return if File.exist?(_file) && File.read(_file) == contents

  File.open(_file, "w+") do |f|
    f << contents
  end
end