Last active
August 20, 2024 11:36
-
-
Save amkisko/78d19706c35214d24308c09a7bbe894e to your computer and use it in GitHub Desktop.
Rails i18n create missing translations using page HTML span hints in pair with rspec to automate the process fully
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
findings = [["translation missing: en.admin_dashboard.sprint_widget.sprint", "Sprint"]] | |
create_translations(findings, locales = ["en", "fi"], dry_run: false) | |
# rspec usage: I18N_CREATE_MISSING=1 bundle exec rspec |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "nokogiri" | |
RSpec.shared_examples_for "html page" do |path: nil, text: nil| | |
let(:parsed_body) { Nokogiri.HTML5(page.body) } | |
if path.present? | |
it "has correct path" do | |
expect(page).to have_current_path(path, ignore_query: true) | |
end | |
end | |
if text.present? | |
it "has correct text" do | |
expect(page).to have_text(text) | |
end | |
end | |
it "has valid html" do | |
expect(parsed_body).to be_a(Nokogiri::HTML::Document) | |
expect(parsed_body.errors).to be_empty | |
end | |
it "has no missing translations" do | |
missing_translations = parsed_body.css("span.translation_missing").map do |span| | |
[span["title"], span.text] | |
end | |
if ENV["I18N_CREATE_MISSING"].present? | |
I18nTools.create_translations(missing_translations, dry_run: false) | |
end | |
expect(missing_translations).to be_empty | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module I18nTools | |
def self.create_translations(findings, locales = I18n.available_locales, dry_run: true, override: false) | |
locales.each do |locale| | |
file_path = "config/locales/#{locale}.yml" | |
next unless File.exist?(file_path) | |
file = YAML.load_file(file_path) | |
findings.each do |finding| | |
cursor = file | |
path = finding[0].gsub("translation missing: ", "").split(".") | |
path[0] = locale | |
path[0..-2].each do |path| | |
cursor = cursor[path] || (cursor[path] = {}) | |
end | |
translation = finding[1] | |
translation_key = path.last | |
cursor[translation_key] = translation if cursor[translation_key].blank? || override | |
puts "#{path.join(".")} => #{translation}" | |
end | |
File.write(file_path, file.to_yaml) unless dry_run | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment