faker
faker copied to clipboard
Locale setting can be ignored
The bug
Depending on how locale is set, it may be ignored in threaded server environments.
In particular, we use Faker at runtime in a deployed environment (using Puma) where a user can press a button and the server generates them fake data in a form.
To Reproduce
- Set up a Rails app with a threaded server (eg Puma)
- In a
lib
file, or an initializer, add a locale setting line:Faker::Config.locale = :'en-GB'
- Make a request to the server for fake data.
- You will receive fake data for the default locale
:en
, which is American (eg Zip codes) not:en-GB
(eg Postcodes)
Cause
The cause is the new threaded safety: https://github.com/faker-ruby/faker/pull/2520 introduced in Faker 2.23.0.
Puma works by preloading the app, then process forking it (and also maybe generating new server threads). From the above reproduction steps, you can see that the Faker locale will be set in the ThreadLocal of the master process Thread.current[:faker_config_locale]
. However, all the threaded child processes do not inherit the ThreadLocal value, so it is blank, and defaults to :en
.
Reverting to Faker 2.22.0 solves the issue.
Possible solution
When the locale is set for the first time, it could become the new default instead of the logic here: https://github.com/faker-ruby/faker/blob/master/lib/faker.rb#L23
Open to other ideas!