Sha256: 851f67e9d28906852deb9972f2e99f9c6dc8d765e285028939b26d6e32c31174

Contents?: true

Size: 1.41 KB

Versions: 15

Compression:

Stored size: 1.41 KB

Contents

# TODO:
#  - Filter frontend keys
#  - minify?
module MnoEnterprise
  module Frontend
    class LocalesGenerator

      def initialize(path)
        @path = path
      end

      # Generate JSON locales
      def generate_json
        translations_hash = get_translations

        translations_hash.each do |locale, translations|
          generate_locale(locale, translations)
        end
      end

      private

      # Return the I18n translation hash
      def get_translations
        I18n.translate(:foo) # Need to do this to force I18n init
        I18n.backend.send(:translations)
      end

      # Write the json file
      def generate_locale(locale_code, translation_hash)
        locale = {}
        flatten_translations('', translation_hash, locale)

        output_file = File.join(@path, "#{locale_code}.locale.json")

        File.open(output_file, 'w') {|f| f.write(JSON.pretty_generate(locale)) }
        puts "--> Generated #{output_file}"
      end

      # Flatten key
      # print_translations("", {foo: {bar: 'baz'}}, locale)
      #  => locale = {'foo.bar' => 'baz'}
      def flatten_translations(prefix, x, locale)
        if x.is_a? Hash
          if (not prefix.empty?)
            prefix += "."
          end
          x.each {|key, value|
            flatten_translations(prefix + key.to_s, value, locale)
          }
        else
          locale.merge!({prefix => x})
        end
      end
    end
  end
end

Version data entries

15 entries across 15 versions & 1 rubygems

Version Path
mno-enterprise-frontend-3.2.1 lib/mno_enterprise/frontend/locales_generator.rb
mno-enterprise-frontend-3.2.0 lib/mno_enterprise/frontend/locales_generator.rb
mno-enterprise-frontend-3.1.4 lib/mno_enterprise/frontend/locales_generator.rb
mno-enterprise-frontend-3.0.7 lib/mno_enterprise/frontend/locales_generator.rb
mno-enterprise-frontend-3.1.3 lib/mno_enterprise/frontend/locales_generator.rb
mno-enterprise-frontend-3.0.6 lib/mno_enterprise/frontend/locales_generator.rb
mno-enterprise-frontend-3.1.2 lib/mno_enterprise/frontend/locales_generator.rb
mno-enterprise-frontend-3.0.5 lib/mno_enterprise/frontend/locales_generator.rb
mno-enterprise-frontend-3.1.1 lib/mno_enterprise/frontend/locales_generator.rb
mno-enterprise-frontend-3.0.4 lib/mno_enterprise/frontend/locales_generator.rb
mno-enterprise-frontend-3.1.0 lib/mno_enterprise/frontend/locales_generator.rb
mno-enterprise-frontend-3.0.3 lib/mno_enterprise/frontend/locales_generator.rb
mno-enterprise-frontend-3.0.2 lib/mno_enterprise/frontend/locales_generator.rb
mno-enterprise-frontend-3.0.1 lib/mno_enterprise/frontend/locales_generator.rb
mno-enterprise-frontend-3.0.0 lib/mno_enterprise/frontend/locales_generator.rb