From af1b437893883dc6e31eacd72bedd760d299cc59 Mon Sep 17 00:00:00 2001 From: Akira Matsuda Date: Tue, 20 Oct 2020 02:04:55 +0900 Subject: [PATCH] Defer loading I18n YAML files until actually translating --- lib/faker.rb | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/lib/faker.rb b/lib/faker.rb index 17a58695ed..981f9f4dc3 100644 --- a/lib/faker.rb +++ b/lib/faker.rb @@ -8,10 +8,19 @@ Dir.glob(File.join(mydir, 'helpers', '*.rb')).sort.each { |file| require file } -I18n.load_path += Dir[File.join(mydir, 'locales', '**/*.yml')] -I18n.reload! if I18n.backend.initialized? - module Faker + @i18n_loaded = nil + + class << self + def load_i18n + unless @i18n_loaded + I18n.load_path += ::Dir[::File.join(__dir__, 'locales', '**/*.yml')] + I18n.reload! if I18n.backend.initialized? + @i18n_loaded = true + end + end + end + class Config @locale = nil @random = nil @@ -21,6 +30,8 @@ class << self attr_writer :random def locale + Faker.load_i18n + # Because I18n.locale defaults to :en, if we don't have :en in our available_locales, errors will happen @locale || (I18n.available_locales.include?(I18n.locale) ? I18n.locale : I18n.available_locales.first) end @@ -150,6 +161,8 @@ def parse(key) # Call I18n.translate with our configured locale if no # locale is specified def translate(*args, **opts) + Faker.load_i18n + opts[:locale] ||= Faker::Config.locale opts[:raise] = true I18n.translate(*args, **opts) @@ -166,6 +179,8 @@ def translate(*args, **opts) # Executes block with given locale set. def with_locale(tmp_locale = nil) + Faker.load_i18n + current_locale = Faker::Config.own_locale Faker::Config.locale = tmp_locale