Skip to content

Instantly share code, notes, and snippets.

@amkisko
Last active August 20, 2024 11:36
Show Gist options
  • Save amkisko/78d19706c35214d24308c09a7bbe894e to your computer and use it in GitHub Desktop.
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
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
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
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