Skip to content

Commit

Permalink
Merge pull request #382 from shayonj/s/thread-reset-middleware
Browse files Browse the repository at this point in the history
Introduce middleware that resets current local thread's config after each request
  • Loading branch information
radar committed Oct 14, 2017
2 parents 5e68c19 + 13d286b commit efc97ba
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 0 deletions.
1 change: 1 addition & 0 deletions lib/i18n.rb
Expand Up @@ -10,6 +10,7 @@ module I18n
autoload :Gettext, 'i18n/gettext'
autoload :Locale, 'i18n/locale'
autoload :Tests, 'i18n/tests'
autoload :Middleware, 'i18n/middleware'

RESERVED_KEYS = [:scope, :default, :separator, :resolve, :object, :fallback, :fallback_in_progress, :format, :cascade, :throw, :raise, :deep_interpolation]
RESERVED_KEYS_PATTERN = /%\{(#{RESERVED_KEYS.join("|")})\}/
Expand Down
15 changes: 15 additions & 0 deletions lib/i18n/middleware.rb
@@ -0,0 +1,15 @@
module I18n
class Middleware

def initialize(app)
@app = app
end

def call(env)
@app.call(env)
ensure
Thread.current[:i18n_config] = I18n::Config.new
end

end
end
24 changes: 24 additions & 0 deletions test/i18n/middleware_test.rb
@@ -0,0 +1,24 @@
require 'test_helper'

class I18nMiddlewareTest < I18n::TestCase
def setup
super
I18n.default_locale = :fr
@app = DummyRackApp.new
@middleware = I18n::Middleware.new(@app)
end

test "middleware initializes new config object after request" do
old_i18n_config_object_id = Thread.current[:i18n_config].object_id
@middleware.call({})

updated_i18n_config_object_id = Thread.current[:i18n_config].object_id
assert_not_equal updated_i18n_config_object_id, old_i18n_config_object_id
end

test "succesfully resets i18n locale to default locale by defining new config" do
@middleware.call({})

assert_equal :fr, I18n.locale
end
end
6 changes: 6 additions & 0 deletions test/test_helper.rb
Expand Up @@ -53,3 +53,9 @@ def locales_dir
File.dirname(__FILE__) + '/test_data/locales'
end
end

class DummyRackApp
def call(env)
I18n.locale = :es
end
end

0 comments on commit efc97ba

Please sign in to comment.