Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is I18n.with_locale threadsafe?

I have created a feature that publish a news with the language of the page's creator.

Here is the code that create the news :

def add_news
  locale = creator.language.blank? ? I18n.locale : creator.language
  I18n.with_locale(locale) do
    title = I18n.t('news.subject')
  end
  create_news({title: title})
end

It works good, the news is created with the good language. But sometimes, a wrong language is used. I have read the sourcecode of i18n (https://github.com/svenfuchs/i18n/blob/master/lib/i18n.rb), and for me the with_local function is not threadsafe. I was very surprised beacause I have read no post on that problem.

So, waht do you think about that ? Threadsafe or not ? Do you know a other solution if so ?

Thanks and br,

Eric

like image 346
elhostis Avatar asked Sep 28 '22 05:09

elhostis


1 Answers

Looks like it is from the Ruby on Rails guides as it is using Thread.current.

Also ran a small (conclusive) experiment:

n = I18n.available_locales.length
10.times do |i|
  loc = I18n.available_locales[i % n]
  Thread.new do
    I18n.with_locale(loc) do
      puts "#{loc} #{I18n.t 'one.of.your.keys'}"
    end
  end
end
like image 103
user4887419 Avatar answered Oct 11 '22 16:10

user4887419