Cache I18nContent translations

This way we avoid fetching each translation every time it's requested.
This reduces the amount of queries in the development logs and also
makes the test suite faster.
This commit is contained in:
Javi Martín
2020-11-20 00:35:24 +01:00
parent 3ce8fa5b95
commit 41dba842a6
3 changed files with 46 additions and 3 deletions

View File

@@ -94,4 +94,12 @@ class I18nContent < ApplicationRecord
budgets.index.section_footer.description budgets.index.section_footer.description
] ]
end 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 end

View File

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

View File

@@ -118,4 +118,41 @@ RSpec.describe I18nContent, type: :model do
}) })
end end
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 end