Skip to content

Commit

Permalink
fixes default locale for new threads (WIP)
Browse files Browse the repository at this point in the history
sets a fallback locale and a default locale
to be copied over to new threads

Co-authored-by: Stefanni Brasil <stefannibrasil@gmail.com>
  • Loading branch information
thdaraujo and Stefanni Brasil committed Oct 16, 2022
1 parent 01b0270 commit 7987810
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 2 deletions.
21 changes: 19 additions & 2 deletions lib/faker.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,17 @@ module Faker
module Config
class << self
def locale=(new_locale)
if new_locale == @fallback_locale
@inital_locale = nil
else
@inital_locale ||= new_locale
end

Thread.current[:faker_config_locale] = new_locale
end

def locale
# Because I18n.locale defaults to :en, if we don't have :en in our available_locales, errors will happen
Thread.current[:faker_config_locale] || (I18n.available_locales.include?(I18n.locale) ? I18n.locale : I18n.available_locales.first)
Thread.current[:faker_config_locale] ||= @inital_locale
end

def own_locale
Expand All @@ -33,6 +38,16 @@ def random=(new_random)
def random
Thread.current[:faker_config_random] || Random
end

def setup!
@fallback_locale = if I18n.available_locales.include?(I18n.locale)
I18n.locale
else
I18n.available_locales.first
end

self.locale = @fallback_locale
end
end
end

Expand Down Expand Up @@ -265,3 +280,5 @@ def disable_enforce_available_locales

# require faker objects
Dir.glob(File.join(mydir, 'faker', '/**/*.rb')).sort.each { |file| require file }

Faker::Config.setup!
41 changes: 41 additions & 0 deletions test/test_determinism.rb
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,47 @@ def test_thread_safety
threads.each(&:join)
end

def test_locale_setting
# if locale is not set, fallback to :en
assert_equal :en, Faker::Config.locale

# locale can be updated initially
# and it becomes the default value
# for new threads
Faker::Config.locale = :pt

assert_equal :pt, Faker::Config.locale

t1 = Thread.new do
# child thread has initial locale equal to
# latest locale set on main thread
# instead of the fallback value
assert_equal :pt, Faker::Config.locale
refute_equal :en, Faker::Config.locale

# child thread can set its own locale
Faker::Config.locale = :es
assert_equal :es, Faker::Config.locale
end

t1.join

# child thread won't change locale of other threads
assert_equal :pt, Faker::Config.locale

t2 = Thread.new do
# initial default locale is copied over to new thread
assert_equal :pt, Faker::Config.locale

Faker::Config.locale = :it
assert_equal :it, Faker::Config.locale
end

t2.join

assert_equal :pt, Faker::Config.locale
end

private

def deterministic_random?(first, method_name)
Expand Down

0 comments on commit 7987810

Please sign in to comment.