Sha256: 69731561579c1dd7ac25f3ef1a212be13a2876c5b2a868cfcdc94e90a0fcf4bc

Contents?: true

Size: 1.32 KB

Versions: 9

Compression:

Stored size: 1.32 KB

Contents

module I18n
  module JS
    class Middleware
      def initialize(app)
        @app = app
      end

      def call(env)
        @cache = nil
        verify_locale_files!
        @app.call(env)
      end

      private
      def cache_path
        @cache_path ||= Rails.root.join("tmp/cache/i18n-js.yml")
      end

      def cache
        @cache ||= begin
          if cache_path.exist?
            YAML.load_file(cache_path) || {}
          else
            {}
          end
        end
      end

      # Check if translations should be regenerated.
      # ONLY REGENERATE when these conditions are met:
      #
      # # Cache file doesn't exist
      # # Translations and cache size are different (files were removed/added)
      # # Translation file has been updated
      #
      def verify_locale_files!
        valid_cache = []
        new_cache = {}

        valid_cache.push cache_path.exist?
        valid_cache.push ::I18n.load_path.uniq.size == cache.size

        ::I18n.load_path.each do |path|
          changed_at = File.mtime(path).to_i
          valid_cache.push changed_at == cache[path]
          new_cache[path] = changed_at
        end

        return if valid_cache.all?

        File.open(cache_path, "w+") do |file|
          file << new_cache.to_yaml
        end

        ::I18n::JS.export
      end
    end
  end
end

Version data entries

9 entries across 9 versions & 2 rubygems

Version Path
i18n-js-pika-3.0.0.rc9 lib/i18n/js/middleware.rb
i18n-js-pika-3.0.0.rc8 lib/i18n/js/middleware.rb
i18n-js-pika-3.0.0.rc7 lib/i18n/js/middleware.rb
i18n-js-pika-3.0.0.rc6 lib/i18n/js/middleware.rb
i18n-js-3.0.0.rc5 lib/i18n/js/middleware.rb
i18n-js-3.0.0.rc4 lib/i18n/js/middleware.rb
i18n-js-3.0.0.rc3 lib/i18n/js/middleware.rb
i18n-js-3.0.0.rc2 lib/i18n/js/middleware.rb
i18n-js-3.0.0.rc1 lib/i18n/js/middleware.rb