Skip to content

Commit

Permalink
Defer loading I18n YAML files until actually translating
Browse files Browse the repository at this point in the history
  • Loading branch information
amatsuda committed Oct 20, 2020
1 parent 684c5ed commit af1b437
Showing 1 changed file with 18 additions and 3 deletions.
21 changes: 18 additions & 3 deletions lib/faker.rb
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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)
Expand All @@ -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

Expand Down

0 comments on commit af1b437

Please sign in to comment.