Sha256: 929aaa978ca126e6be8c59c9829902246efb6546b453214f30e309dcc6fc440b

Contents?: true

Size: 1.17 KB

Versions: 5

Compression:

Stored size: 1.17 KB

Contents

require "i18n/js/formatters/base"

module I18n
  module JS
    module Formatters
      class JS < Base
        JSON_ESCAPE_MAP = {
          "'" => "\\'",
          "\\" => "\\\\"
        }.freeze
        private_constant :JSON_ESCAPE_MAP

        def format(translations)
          contents = header
          translations.each do |locale, translations_for_locale|
            contents << line(locale, format_json(translations_for_locale))
          end
          contents << (@suffix || '')
        end

        protected

        def header
          text = @prefix || ''
          text + %(#{@namespace}.translations || (#{@namespace}.translations = {});\n)
        end

        def line(locale, translations)
          json_literal = @pretty_print ? translations : %(JSON.parse('#{translations.gsub(/#{Regexp.union(JSON_ESCAPE_MAP.keys)}/){|match| JSON_ESCAPE_MAP.fetch(match) }}'))
          if @js_extend
            %(#{@namespace}.translations["#{locale}"] = I18n.extend((#{@namespace}.translations["#{locale}"] || {}), #{json_literal});\n)
          else
            %(#{@namespace}.translations["#{locale}"] = #{json_literal};\n)
          end
        end
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
i18n-js-3.9.2 lib/i18n/js/formatters/js.rb
i18n-js-3.9.1 lib/i18n/js/formatters/js.rb
i18n-js-3.9.0 lib/i18n/js/formatters/js.rb
i18n-js-3.8.4 lib/i18n/js/formatters/js.rb
i18n-js-3.8.3 lib/i18n/js/formatters/js.rb