Merge pull request #4264 from consul/cache_i18n_content

Cache I18nContent translations
This commit is contained in:
Javi Martín
2020-12-15 18:44:33 +01:00
committed by GitHub
3 changed files with 50 additions and 3 deletions

View File

@@ -94,4 +94,12 @@ class I18nContent < ApplicationRecord
budgets.index.section_footer.description
]
end
def self.translations_hash(locale)
Rails.cache.fetch(translation_class.where(locale: locale)) do
all.map do |content|
[content.key, translation_class.find_by(i18n_content_id: content, locale: locale)&.value]
end.to_h
end
end
end

View File

@@ -9,9 +9,11 @@ module ActionView
def t(key, options = {})
current_locale = options[:locale].presence || I18n.locale
i18_content = I18nContent.find_by(key: key)
translation = I18nContentTranslation.find_by(i18n_content_id: i18_content&.id,
locale: current_locale)&.value
@i18n_content_translations ||= {}
@i18n_content_translations[current_locale] ||= I18nContent.translations_hash(current_locale)
translation = @i18n_content_translations[current_locale][key]
if translation.present?
translation % options
else

View File

@@ -118,4 +118,41 @@ RSpec.describe I18nContent, type: :model do
})
end
end
describe ".translations_hash" do
let!(:content) { create(:i18n_content, key: "great", value_en: "Custom great", value_es: nil) }
it "gets the translations" do
expect(I18nContent.translations_hash(:en)["great"]).to eq "Custom great"
end
it "does not use fallbacks, so YAML files will be used instead" do
expect(I18nContent.translations_hash(:es)["great"]).to be nil
end
it "gets new translations after values are cached" do
expect(I18nContent.translations_hash(:en)["great"]).to eq "Custom great"
create(:i18n_content, key: "amazing", value_en: "Custom amazing")
expect(I18nContent.translations_hash(:en)["great"]).to eq "Custom great"
expect(I18nContent.translations_hash(:en)["amazing"]).to eq "Custom amazing"
end
it "gets the updated translation after values are cached" do
expect(I18nContent.translations_hash(:en)["great"]).to eq "Custom great"
content.update!(value_en: "New great")
expect(I18nContent.translations_hash(:en)["great"]).to eq "New great"
end
it "does not get removed translations after values are cached" do
expect(I18nContent.translations_hash(:en)["great"]).to eq "Custom great"
I18nContent.delete_all
expect(I18nContent.translations_hash(:en)["great"]).to be nil
end
end
end