Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Keep the store content locale in request state, not I18n.default_locale (#14298)

Damian Legawiecd02d6002c5a1
diff --git a/CLAUDE.md b/CLAUDE.md
index 5ccc5ab7f1..2992132bb0 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -616,6 +616,7 @@ Re-run `parallel_setup` after schema changes.
- Prefer `build` over `create` for speed
- Factories live in `lib/spree/testing_support/factories/`
- ALWAYS use factories in tests, never call `Model#create` directly
+- ALWAYS run parallel tests if running full test suite, if there are any failures repeat the failed examples seperately and confirm they really fail before investigating
- Pragmatic — no tests for standard Rails validations, only custom ones
- Controller specs: always add `render_views`, use `stub_authorization!` for auth
- Use controller specs for testing edge cases, API integration tests are only for happy path/simple 422 failures to generate OpenAPI examples; otherwise they get too brittle and high-maintenance
diff --git a/spree/admin/app/controllers/concerns/spree/admin/locale_concern.rb b/spree/admin/app/controllers/concerns/spree/admin/locale_concern.rb
index aa5b092ab2..0ec4adf2b7 100644
--- a/spree/admin/app/controllers/concerns/spree/admin/locale_concern.rb
+++ b/spree/admin/app/controllers/concerns/spree/admin/locale_concern.rb
@@ -3,15 +3,18 @@ module Spree
# Decouples the admin UI language from the store's content language.
#
# `I18n.locale` drives the UI chrome (`Spree.t` labels) and follows the
- # staff member's chosen admin language. `Mobility.locale` drives translated
- # record fields (product/store names) and is pinned to the store's content
- # locale — otherwise switching the admin to, say, Polish would make every
+ # staff member's chosen admin language. `Mobility.locale` and
+ # `Spree::Current.content_locale` drive translated record fields
+ # (product/store names) and are pinned to the store's content locale —
+ # otherwise switching the admin to, say, Polish would make every
# Mobility-backed field fall back to nil for stores that don't translate
# their catalog into Polish.
#
- # Shared by `Spree::Admin::BaseController` and `UserSessionsController`; the
- # latter subclasses `Devise::SessionsController`, so it can't inherit this
- # via the controller chain — hence a concern both include.
+ # Shared by `Spree::Admin::BaseController` and the Devise-based pre-auth
+ # controllers (`UserSessionsController`), which can't inherit admin
+ # behavior via the controller chain — hence a concern both include.
+ # Devise-based includers opt into the login-screen locale handling with
+ # `before_action :set_login_locale`.
module LocaleConcern
extend ActiveSupport::Concern
@@ -22,27 +25,36 @@ module Spree
private
- # The store's content locale — the language record content (product names,
- # etc.) is authored in — independent of the chosen admin UI language.
- def content_locale
- (defined?(current_store) && current_store&.default_locale.presence) || I18n.default_locale
- end
-
- # Read all record content in the store's content locale, independent of
- # the chosen UI language.
+ # Pin content reads to the store's content locale (its default locale),
+ # independent of the chosen UI language. Request-local state only — the
+ # content locale must never be written to the process-global
+ # `I18n.default_locale`, which every thread in the server process shares.
+ # The fallback for storeless hosts lives in the
+ # `Spree::Current#content_locale` reader.
def pin_content_locale!
- Mobility.locale = content_locale
+ Spree::Current.content_locale = (current_store&.default_locale if defined?(current_store))
+ Mobility.locale = Spree::Current.content_locale
end
- # Keep `I18n.default_locale` on the store's content locale so it matches
- # `Mobility.locale` (set by `pin_content_locale!`). The admin overrides
- # `default_locale` to return the UI language, which the inherited
- # `set_locale` leaks into the process-global `I18n.default_locale`. When it
- # diverges from `Mobility.locale`, Mobility's `column_fallback` JOINs the
- # translations table instead of reading the base column, breaking the
- # admin's ordered + `DISTINCT` listings.
- def align_i18n_default_locale_to_content!
- I18n.default_locale = content_locale
+ # Pre-auth locale handling for Devise-based screens, where the
+ # `set_locale` before_action from `Spree::Core::ControllerHelpers::Locale`
+ # never runs. A supported `?locale=` is applied and persisted; an
+ # unsupported one is ignored rather than shadowing an already-valid
+ # cookie. Falls back to the cookie set on a previous visit, then to the
+ # application default — always an explicit assignment, so a plain visit
+ # can never render in whatever locale the thread's previous request
+ # happened to set.
+ def set_login_locale
+ pin_content_locale!
+
+ if supported_admin_locale?(params[:locale])
+ cookies[ADMIN_LOCALE_COOKIE] = { value: params[:locale], expires: 1.year }
+ I18n.locale = params[:locale]
+ elsif supported_admin_locale?(admin_locale_cookie)
+ I18n.locale = admin_locale_cookie
+ else
+ I18n.locale = I18n.default_locale
+ end
end
def admin_user_selected_locale
diff --git a/spree/admin/app/controllers/spree/admin/base_controller.rb b/spree/admin/app/controllers/spree/admin/base_controller.rb
index d531615cc1..e871fcc2e5 100644
--- a/spree/admin/app/controllers/spree/admin/base_controller.rb
+++ b/spree/admin/app/controllers/spree/admin/base_controller.rb
@@ -88,16 +88,12 @@ module Spree
end
# Set the UI language (`I18n.locale`, via super) while keeping content
- # reads on the store's locale — see Spree::Admin::LocaleConcern.
- #
- # `super` derives `I18n.default_locale` from the overridden `default_locale`
- # (the admin UI language), but `I18n.default_locale` must track the store's
- # *content* locale so it matches `Mobility.locale`; otherwise Mobility JOINs
- # the translations table instead of the base column and ordered + `DISTINCT`
- # listings raise. Re-align it immediately after `super`.
+ # reads on the store's locale — see Spree::Admin::LocaleConcern. `super`
+ # records the content locale in `Spree::Current` (the admin overrides
+ # `default_locale` to the UI language, but `content_locale` stays on the
+ # store's default), and `pin_content_locale!` aligns Mobility with it.
def set_locale
super
- align_i18n_default_locale_to_content!
pin_content_locale!
sync_pagy_locale!
end
diff --git a/spree/admin/app/controllers/spree/admin/user_sessions_controller.rb b/spree/admin/app/controllers/spree/admin/user_sessions_controller.rb
index 1b9e055982..671a23641b 100644
--- a/spree/admin/app/controllers/spree/admin/user_sessions_controller.rb
+++ b/spree/admin/app/controllers/spree/admin/user_sessions_controller.rb
@@ -11,10 +11,8 @@ module Spree
# This controller inherits from Devise::SessionsController, so the
# `set_locale` before_action from Spree::Core::ControllerHelpers::Locale
- # (mixed into Spree::Admin::BaseController) never runs here. Honor the
- # pre-auth `?locale=` param ourselves so the login screen's language
- # switcher works before any user is signed in, persisting the choice in a
- # cookie so it carries into the authenticated session after sign-in.
+ # (mixed into Spree::Admin::BaseController) never runs here — opt into
+ # the concern's pre-auth locale handling instead (see LocaleConcern).
before_action :set_login_locale
auth_rate_limit :rate_limit_login, redirect_to: -> { new_session_path(resource_name) }
@@ -34,22 +32,6 @@ module Spree
def translation_scope
'devise.user_sessions'
end
-
- private
-
- def set_login_locale
- pin_content_locale!
-
- # A supported `?locale=` is applied and persisted; an unsupported one is
- # ignored rather than shadowing an already-valid cookie. Falls back to
- # the cookie set on a previous visit.
- if supported_admin_locale?(params[:locale])
- cookies[ADMIN_LOCALE_COOKIE] = { value: params[:locale], expires: 1.year }
- I18n.locale = params[:locale]
- elsif supported_admin_locale?(admin_locale_cookie)
- I18n.locale = admin_locale_cookie
- end
- end
end
end
end
diff --git a/spree/admin/spec/controllers/spree/admin/base_controller_spec.rb b/spree/admin/spec/controllers/spree/admin/base_controller_spec.rb
index 8b4c171b90..4fcac94f5e 100644
--- a/spree/admin/spec/controllers/spree/admin/base_controller_spec.rb
+++ b/spree/admin/spec/controllers/spree/admin/base_controller_spec.rb
@@ -40,21 +40,14 @@ describe Spree::Admin::BaseController, type: :controller do
expect(I18n.locale).to eq(:de)
end
- it 'keeps I18n.default_locale on the content locale, not the admin UI locale' do
- # `I18n.default_locale` must track the store content locale so it matches
- # `Mobility.locale`; binding it to the admin UI language desyncs Mobility
- # and breaks ordered + DISTINCT listings.
- get :index
- expect(I18n.default_locale.to_s).to eq(store.default_locale)
- end
- end
-
- context 'when preferred_admin_locale is not set' do
- before { allow(store).to receive(:preferred_admin_locale).and_return(nil) }
-
- it 'falls back to store default_locale' do
- get :index
- expect(I18n.default_locale.to_s).to eq(store.default_locale)
+ it 'keeps the content locale on the store locale, not the admin UI locale' do
+ # `Spree::Current.content_locale` must track the store content locale so
+ # it matches `Mobility.locale`; binding it to the admin UI language
+ # desyncs Mobility and breaks ordered + DISTINCT listings.
+ # (Direct call: the test-request executor resets Spree::Current before
+ # a post-`get` assertion could see it.)
+ controller.send(:set_locale)
+ expect(Spree::Current.content_locale).to eq(store.default_locale)
end
end
@@ -69,9 +62,9 @@ describe Spree::Admin::BaseController, type: :controller do
expect(I18n.locale).to eq(:en)
end
- it 'keeps I18n.default_locale on the market/content locale' do
- get :index
- expect(I18n.default_locale).to eq(:fr)
+ it 'keeps the content locale on the store locale' do
+ controller.send(:set_locale)
+ expect(Spree::Current.content_locale).to eq('fr')
end
end
end
@@ -170,13 +163,17 @@ describe Spree::Admin::BaseController, type: :controller do
expect(Mobility.locale).to eq(:fr)
end
- it 'keeps I18n.default_locale aligned with Mobility (the content locale)' do
+ it 'keeps the request content locale aligned with Mobility' do
# Mobility's column_fallback reads the base column only when the locale
- # equals I18n.default_locale; if they diverge, translated listings JOIN the
- # translations table and ordered + DISTINCT queries raise.
- get :index
- expect(I18n.default_locale).to eq(:fr)
- expect(I18n.default_locale).to eq(Mobility.locale)
+ # equals the request's content locale; if they diverge, translated
+ # listings JOIN the translations table and ordered + DISTINCT queries raise.
+ controller.send(:set_locale)
+ expect(Spree::Current.content_locale).to eq('fr')
+ expect(Mobility.locale).to eq(:fr)
+ end
+
+ it 'leaves the process-global I18n.default_locale untouched' do
+ expect { get :index }.not_to change(I18n, :default_locale)
end
end
diff --git a/spree/admin/spec/controllers/spree/admin/user_sessions_controller_spec.rb b/spree/admin/spec/controllers/spree/admin/user_sessions_controller_spec.rb
index 19ef016b06..7ce2893cb7 100644
--- a/spree/admin/spec/controllers/spree/admin/user_sessions_controller_spec.rb
+++ b/spree/admin/spec/controllers/spree/admin/user_sessions_controller_spec.rb
@@ -76,4 +76,15 @@ describe Spree::Admin::UserSessionsController, type: :controller do
expect(ui_locale).to eq('fr')
end
end
+
+ context 'with no param and no cookie' do
+ it 'renders the application default locale even when the thread carries a stale one' do
+ # Server threads are reused across requests; without an explicit
+ # assignment the login screen would render in whatever locale the
+ # previous request on this thread happened to set.
+ I18n.locale = :fr
+ get :show
+ expect(ui_locale).to eq(I18n.default_locale.to_s)
+ end
+ end
end
diff --git a/spree/admin/spec/spec_helper.rb b/spree/admin/spec/spec_helper.rb
index 96d0b98637..7d9a8843c2 100644
--- a/spree/admin/spec/spec_helper.rb
+++ b/spree/admin/spec/spec_helper.rb
@@ -103,6 +103,7 @@ RSpec.configure do |config|
config.before(:each) do
reset_spree_preferences
+ Spree::Current.reset
end
config.include FactoryBot::Syntax::Methods
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/locale_and_currency.rb b/spree/api/app/controllers/concerns/spree/api/v3/locale_and_currency.rb
index b6fe348090..8e36f20088 100644
--- a/spree/api/app/controllers/concerns/spree/api/v3/locale_and_currency.rb
+++ b/spree/api/app/controllers/concerns/spree/api/v3/locale_and_currency.rb
@@ -114,9 +114,12 @@ module Spree
private
- # Sets +I18n.locale+ and +Spree::Current.locale+ from the resolved locale.
+ # Sets +I18n.locale+ and +Spree::Current.locale+ from the resolved
+ # locale, and records the request's content locale — the store's
+ # default locale, in which base (untranslated) columns are authored.
def set_locale
Spree::Current.locale = current_locale
+ Spree::Current.content_locale = current_store&.default_locale
I18n.locale = current_locale
end
diff --git a/spree/api/app/services/spree/api/v3/filters_aggregator.rb b/spree/api/app/services/spree/api/v3/filters_aggregator.rb
index 6ad833f00d..09ea41123a 100644
--- a/spree/api/app/services/spree/api/v3/filters_aggregator.rb
+++ b/spree/api/app/services/spree/api/v3/filters_aggregator.rb
@@ -87,9 +87,9 @@ module Spree
type_ids = option_types.map(&:id)
# Pluck only the columns we need — avoids instantiating thousands of AR models.
- # Force default locale so Mobility returns column values (not translations);
+ # Force the content locale so Mobility returns column values (not translations);
# translated labels are overlaid separately via load_option_value_translations.
- ov_rows = Mobility.with_locale(I18n.default_locale) do
+ ov_rows = Mobility.with_locale(Spree::Current.content_locale) do
Spree::OptionValue
.where(option_type_id: type_ids)
.order(:position)
@@ -144,10 +144,10 @@ module Spree
end
# Load translated presentations for option values.
- # Returns { option_value_id => translated_presentation } or empty hash when using the default locale.
+ # Returns { option_value_id => translated_presentation } or empty hash when using the content locale.
def load_option_value_translations(ov_ids)
locale = Spree::Current.locale || I18n.locale.to_s
- return {} if locale.to_s == I18n.default_locale.to_s
+ return {} if locale.to_s == Spree::Current.content_locale
Spree::OptionValue::Translation
.where(spree_option_value_id: ov_ids, locale: locale)
diff --git a/spree/core/app/models/concerns/spree/presentation_translatable.rb b/spree/core/app/models/concerns/spree/presentation_translatable.rb
index 3d5d678083..3bcc49d98e 100644
--- a/spree/core/app/models/concerns/spree/presentation_translatable.rb
+++ b/spree/core/app/models/concerns/spree/presentation_translatable.rb
@@ -11,7 +11,7 @@ module Spree
TRANSLATABLE_FIELDS = %i[presentation].freeze
included do
- translates(*TRANSLATABLE_FIELDS, column_fallback: !Spree.always_use_translations?)
+ translates(*TRANSLATABLE_FIELDS, column_fallback: Spree.mobility_column_fallback)
self::Translation.class_eval do
normalizes :presentation, with: ->(value) { value&.to_s&.squish&.presence }
diff --git a/spree/core/app/models/spree/current.rb b/spree/core/app/models/spree/current.rb
index 3e2c36e213..844358b775 100644
--- a/spree/core/app/models/spree/current.rb
+++ b/spree/core/app/models/spree/current.rb
@@ -4,7 +4,7 @@ module Spree
# All attributes are automatically reset between requests by Rails.
# Fallback chains ensure sensible defaults when attributes are not explicitly set.
class Current < ::ActiveSupport::CurrentAttributes
- attribute :store, :channel, :market, :currency, :locale, :zone, :default_tax_zone, :price_lists, :global_pricing_context
+ attribute :store, :channel, :market, :currency, :locale, :content_locale, :zone, :default_tax_zone, :price_lists, :global_pricing_context
resets { @default_tax_zone_loaded = false }
@@ -38,6 +38,17 @@ module Spree
super || market&.default_locale.presence || store&.default_locale.presence || I18n.default_locale.to_s
end
+ # Returns the locale that base (untranslated) record columns are authored
+ # in for the current request — the current store's default locale. It is
+ # assigned per request alongside +I18n.locale+ and must never be written
+ # to the process-global +I18n.default_locale+, which every thread in the
+ # server process shares. Outside a request it falls back to the
+ # application default locale.
+ # @return [String] locale code, e.g. +"en"+, +"de"+
+ def content_locale
+ super.presence || I18n.default_locale.name
+ end
+
# Returns the current tax zone.
# Fallback: market's tax zone (from default country) -> global default tax zone.
# @return [Spree::Zone, nil]
diff --git a/spree/core/app/models/spree/policy.rb b/spree/core/app/models/spree/policy.rb
index 545334613c..0b44550b1a 100644
--- a/spree/core/app/models/spree/policy.rb
+++ b/spree/core/app/models/spree/policy.rb
@@ -22,7 +22,7 @@ module Spree
#
TRANSLATABLE_FIELDS = %i[name body].freeze
RICH_TEXT_TRANSLATABLE_FIELDS = %i[body].freeze
- translates(*TRANSLATABLE_FIELDS, column_fallback: !Spree.always_use_translations?)
+ translates(*TRANSLATABLE_FIELDS, column_fallback: Spree.mobility_column_fallback)
#
# ActionText
diff --git a/spree/core/app/models/spree/product.rb b/spree/core/app/models/spree/product.rb
index 5ff07545bf..390dea8aeb 100644
--- a/spree/core/app/models/spree/product.rb
+++ b/spree/core/app/models/spree/product.rb
@@ -57,7 +57,7 @@ module Spree
TRANSLATABLE_FIELDS = %i[name description slug meta_description meta_title].freeze
RICH_TEXT_TRANSLATABLE_FIELDS = %i[description].freeze
- translates(*TRANSLATABLE_FIELDS, column_fallback: !Spree.always_use_translations?)
+ translates(*TRANSLATABLE_FIELDS, column_fallback: Spree.mobility_column_fallback)
self::Translation.class_eval do
normalizes :name, :meta_title, with: ->(value) { value&.to_s&.squish&.presence }
diff --git a/spree/core/app/models/spree/store.rb b/spree/core/app/models/spree/store.rb
index 105efce3fa..3c6a8b20ed 100644
--- a/spree/core/app/models/spree/store.rb
+++ b/spree/core/app/models/spree/store.rb
@@ -28,7 +28,7 @@ module Spree
#
TRANSLATABLE_FIELDS = %i[name meta_description meta_keywords seo_title customer_support_email
address contact_phone].freeze
- translates(*TRANSLATABLE_FIELDS, column_fallback: !Spree.always_use_translations?)
+ translates(*TRANSLATABLE_FIELDS, column_fallback: Spree.mobility_column_fallback)
self::Translation.class_eval do
acts_as_paranoid
# deleted translation values still need to be accessible - remove deleted_at scope
diff --git a/spree/core/app/models/spree/taxon.rb b/spree/core/app/models/spree/taxon.rb
index 70710d7289..afd90df740 100644
--- a/spree/core/app/models/spree/taxon.rb
+++ b/spree/core/app/models/spree/taxon.rb
@@ -156,7 +156,7 @@ module Spree
#
TRANSLATABLE_FIELDS = %i[name pretty_name description permalink].freeze
RICH_TEXT_TRANSLATABLE_FIELDS = %i[description].freeze
- translates(*TRANSLATABLE_FIELDS, column_fallback: !Spree.always_use_translations?)
+ translates(*TRANSLATABLE_FIELDS, column_fallback: Spree.mobility_column_fallback)
#
# Action Text
diff --git a/spree/core/app/models/spree/taxonomy.rb b/spree/core/app/models/spree/taxonomy.rb
index 076423d8c3..447811e14f 100644
--- a/spree/core/app/models/spree/taxonomy.rb
+++ b/spree/core/app/models/spree/taxonomy.rb
@@ -8,7 +8,7 @@ module Spree
include Spree::SingleStoreResource
TRANSLATABLE_FIELDS = %i[name].freeze
- translates(*TRANSLATABLE_FIELDS, column_fallback: !Spree.always_use_translations?)
+ translates(*TRANSLATABLE_FIELDS, column_fallback: Spree.mobility_column_fallback)
acts_as_list
diff --git a/spree/core/lib/mobility/plugins/store_based_fallbacks.rb b/spree/core/lib/mobility/plugins/store_based_fallbacks.rb
index 85dac38553..71de3a7a95 100644
--- a/spree/core/lib/mobility/plugins/store_based_fallbacks.rb
+++ b/spree/core/lib/mobility/plugins/store_based_fallbacks.rb
@@ -1,6 +1,5 @@
# frozen_string_literal: true
-require 'concurrent'
require 'mobility'
# The default implementation in the Mobility gem requires fallbacks to be defined when booting the application.
@@ -8,15 +7,18 @@ require 'mobility'
# The implementation is based on the default fallbacks plugin, with some changes around fetching the list of fallbacks to be used.
# https://github.com/shioyama/mobility/blob/master/lib/mobility/plugins/fallbacks.rb
module Mobility
- @store_based_fallbacks = Concurrent::ThreadLocalVar.new(I18n::Locale::Fallbacks.new)
-
class << self
+ # Request-scoped via RequestStore (like Mobility.locale), so one request's
+ # store fallbacks can't leak into the next request served by the same
+ # thread. Outside a request RequestStore degrades to plain per-thread
+ # storage; Spree::BaseMailer#with_store_locale restores the previous value
+ # around mail rendering.
def store_based_fallbacks
- @store_based_fallbacks.value
+ RequestStore.store[:mobility_store_based_fallbacks] ||= I18n::Locale::Fallbacks.new
end
def store_based_fallbacks=(value)
- @store_based_fallbacks.value = value
+ RequestStore.store[:mobility_store_based_fallbacks] = value
end
end
diff --git a/spree/core/lib/spree/core.rb b/spree/core/lib/spree/core.rb
index b4a28f05aa..f4fafaf4c6 100644
--- a/spree/core/lib/spree/core.rb
+++ b/spree/core/lib/spree/core.rb
@@ -165,7 +165,19 @@ module Spree
end
def self.use_translations?
- Spree::Config.always_use_translations || I18n.default_locale != I18n.locale
+ Spree::Config.always_use_translations || Spree::Current.content_locale != I18n.locale.name
+ end
+
+ # Mobility +column_fallback+ option shared by every translatable model:
+ # read, write and query the base (untranslated) column when the target
+ # locale is the request's content locale — see Spree::Current#content_locale.
+ # Evaluated on every translated attribute read, so it must stay
+ # allocation-free and must not touch the database (Symbol#name returns the
+ # frozen interned string; Mobility always passes Symbol locales).
+ def self.mobility_column_fallback
+ return false if always_use_translations?
+
+ ->(locale) { locale.name == Spree::Current.content_locale }
end
# Used to configure Spree.
diff --git a/spree/core/lib/spree/core/controller_helpers/locale.rb b/spree/core/lib/spree/core/controller_helpers/locale.rb
index 634aa50213..048f8bbd64 100644
--- a/spree/core/lib/spree/core/controller_helpers/locale.rb
+++ b/spree/core/lib/spree/core/controller_helpers/locale.rb
@@ -19,7 +19,10 @@ module Spree
end
def set_locale
- I18n.default_locale = default_locale unless Spree.always_use_translations?
+ # Request-local content locale — the fallback for storeless hosts
+ # lives in the Spree::Current#content_locale reader; never write the
+ # process-global I18n.default_locale, which all threads share.
+ Spree::Current.content_locale = current_store&.default_locale
I18n.locale = current_locale
end
diff --git a/spree/core/lib/spree/core/engine.rb b/spree/core/lib/spree/core/engine.rb
index 33ecdf9cd9..8e0c76b93e 100644
--- a/spree/core/lib/spree/core/engine.rb
+++ b/spree/core/lib/spree/core/engine.rb
@@ -65,6 +65,18 @@ module Spree
Spree::Deprecation = ActiveSupport::Deprecation.new('6.0', 'Spree')
end
+ # I18n's config lives in fiber/thread-local storage that survives across
+ # requests on reused server threads, so a request that never assigns its
+ # own locale would render in whatever locale the previous request on the
+ # same thread set. The i18n gem ships a middleware that resets it after
+ # every request; Rails does not install it by default. Mobility's request
+ # state needs no counterpart here — Mobility.locale and Spree's
+ # Mobility.store_based_fallbacks live in RequestStore, which is cleared
+ # per request by request_store's own middleware.
+ initializer 'spree.locale_state_reset' do |app|
+ app.middleware.use ::I18n::Middleware
+ end
+
initializer 'spree.register.subscribers', before: :load_config_initializers do |app|
# Initialize subscribers array early so engines can add subscribers via initializers
app.config.spree.subscribers = []
diff --git a/spree/core/spec/lib/spree/content_locale_spec.rb b/spree/core/spec/lib/spree/content_locale_spec.rb
new file mode 100644
index 0000000000..c895c66082
--- /dev/null
+++ b/spree/core/spec/lib/spree/content_locale_spec.rb
@@ -0,0 +1,80 @@
+require 'spec_helper'
+
+# The request's content locale (Spree::Current.content_locale) carries "which
+# locale is authored in base columns" through request-local state. These specs
+# pin the contract that replaced the old per-request mutation of the
+# process-global I18n.default_locale, which is shared by every thread in the
+# server process and leaked one request's locale into others.
+RSpec.describe 'content locale request state' do
+ describe 'Spree.use_translations?' do
+ it 'is false when the current locale matches the content locale' do
+ Spree::Current.content_locale = 'de'
+
+ I18n.with_locale(:de) { expect(Spree.use_translations?).to be(false) }
+ end
+
+ it 'is true when the current locale differs from the content locale' do
+ Spree::Current.content_locale = 'de'
+
+ I18n.with_locale(:en) { expect(Spree.use_translations?).to be(true) }
+ end
+
+ it 'defaults the content locale to the application default outside a request' do
+ I18n.with_locale(I18n.default_locale) { expect(Spree.use_translations?).to be(false) }
+ end
+
+ it 'is always true when always_use_translations is enabled' do
+ allow(Spree::Config).to receive(:always_use_translations).and_return(true)
+ Spree::Current.content_locale = I18n.locale.to_s
+
+ expect(Spree.use_translations?).to be(true)
+ end
+ end
+
+ describe 'Spree.mobility_column_fallback' do
+ it 'targets the base column only for the request content locale' do
+ column_fallback = Spree.mobility_column_fallback
+ Spree::Current.content_locale = 'de'
+
+ expect(column_fallback.call(:de)).to be(true)
+ expect(column_fallback.call(:en)).to be(false)
+ end
+
+ it 'disables the base-column fallback entirely when always_use_translations is enabled' do
+ allow(Spree::Config).to receive(:always_use_translations).and_return(true)
+
+ expect(Spree.mobility_column_fallback).to be(false)
+ end
+ end
+
+ describe 'translated attribute reads' do
+ it 'read the base column for the content locale and the translation table otherwise' do
+ product = create(:product, name: 'Base name')
+ product.translations.create!(locale: 'de', name: 'German translation')
+
+ # Default content locale (application default): :de reads the translation.
+ expect(Mobility.with_locale(:de) { Spree::Product.find(product.id).name }).to eq('German translation')
+
+ # Content locale :de (a request for a German store): :de reads the base column.
+ Spree::Current.content_locale = 'de'
+ expect(Mobility.with_locale(:de) { Spree::Product.find(product.id).name }).to eq('Base name')
+ end
+ end
+
+ describe 'locale state reset between requests' do
+ it "installs the i18n gem's config-resetting middleware" do
+ # I18n.locale lives in fiber-local storage that survives across requests
+ # on reused server threads; the gem's middleware resets it per request.
+ expect(Rails.application.middleware.map(&:name)).to include('I18n::Middleware')
+ end
+
+ it 'request-scopes store-based Mobility fallbacks so RequestStore clears them per request' do
+ custom_fallbacks = I18n::Locale::Fallbacks.new(:de)
+ Mobility.store_based_fallbacks = custom_fallbacks
+
+ RequestStore.clear!
+
+ expect(Mobility.store_based_fallbacks).not_to be(custom_fallbacks)
+ end
+ end
+end
diff --git a/spree/core/spec/lib/spree/core/controller_helpers/locale_spec.rb b/spree/core/spec/lib/spree/core/controller_helpers/locale_spec.rb
index fe108f11a4..d801b2dd0f 100644
--- a/spree/core/spec/lib/spree/core/controller_helpers/locale_spec.rb
+++ b/spree/core/spec/lib/spree/core/controller_helpers/locale_spec.rb
@@ -117,33 +117,22 @@ describe Spree::Core::ControllerHelpers::Locale, type: :controller do
let!(:store) { create :store, default: true, default_locale: 'de', supported_locales: 'en,pl,de' }
before do
- I18n.default_locale = :en
I18n.locale = :en
end
after do
- I18n.default_locale = :en
I18n.locale = :en
end
- it 'sets the default and the current locale' do
+ it 'sets the current locale and records the content locale request-locally' do
set_locale
- expect(I18n.default_locale).to eq(:de)
expect(I18n.locale).to eq(:pl)
+ expect(Spree::Current.content_locale).to eq('de')
end
- context 'when always using translations' do
- before do
- allow(Spree::Config).to receive(:always_use_translations).and_return(true)
- end
-
- it 'sets only the current locale' do
- set_locale
-
- expect(I18n.default_locale).to eq(:en)
- expect(I18n.locale).to eq(:pl)
- end
+ it 'never mutates the process-global I18n.default_locale, which all threads share' do
+ expect { set_locale }.not_to change(I18n, :default_locale)
end
end
end
diff --git a/spree/core/spec/models/spree/current_spec.rb b/spree/core/spec/models/spree/current_spec.rb
index 0758ae0082..db194333cf 100644
--- a/spree/core/spec/models/spree/current_spec.rb
+++ b/spree/core/spec/models/spree/current_spec.rb
@@ -148,6 +148,30 @@ RSpec.describe Spree::Current do
end
end
+ describe '#content_locale' do
+ context 'when content_locale is set' do
+ before { described_class.content_locale = 'de' }
+
+ it 'returns the set content locale' do
+ expect(described_class.content_locale).to eq('de')
+ end
+ end
+
+ context 'when content_locale is not set' do
+ it 'falls back to the application default locale' do
+ expect(described_class.content_locale).to eq(I18n.default_locale.to_s)
+ end
+
+ it 'does not fall back to the store default locale' do
+ # Outside a request nothing assigns the content locale; deriving it
+ # from the store would silently change how jobs and rake tasks read
+ # translated attributes.
+ create(:store, default: true, default_locale: 'de')
+ expect(described_class.content_locale).to eq(I18n.default_locale.to_s)
+ end
+ end
+ end
+
describe '#market' do
context 'when market is set' do
let(:market) { create(:market) }