faker icon indicating copy to clipboard operation
faker copied to clipboard

Locale setting can be ignored

Open hlascelles opened this issue 2 years ago • 0 comments

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

  1. Set up a Rails app with a threaded server (eg Puma)
  2. In a lib file, or an initializer, add a locale setting line: Faker::Config.locale = :'en-GB'
  3. Make a request to the server for fake data.
  4. 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!

hlascelles avatar Sep 15 '22 11:09 hlascelles