Skip to content

Instantly share code, notes, and snippets.

@sixtyfive
Created May 29, 2016 23:53
Show Gist options
  • Save sixtyfive/2ebc627f734e9da723c30d58ac38eaf1 to your computer and use it in GitHub Desktop.
Save sixtyfive/2ebc627f734e9da723c30d58ac38eaf1 to your computer and use it in GitHub Desktop.
I loved this code. Unfortunately I can't use it anymore. May it rest in peace here.
require 'fileutils'
namespace :i18n do
desc 'collect all translation keys from Ruby/HAML files and fill translations table with them'
task :collect_translations => :environment do
def each_translation_key
return to_enum(__method__) unless block_given? # Make this method into an enumerator.
Dir.glob(Rails.root.join('app', '**', '*.{rb,haml}')) do |path| # Rails.root is a Pathname!
File.read(path).scan(/_\(['"](.*?)['"]\)/) do |result| # Because of the (.*) group,
yield result.first # .scan will return a 1-item array!
end
end
end
each_translation_key do |key|
I18n.available_locales.each do |locale|
# I18n::Backend::ActiveRecord::* does NOT behave like a normal AR object!
begin
t = Translation.where(key: key, locale: locale).first!
puts "#{locale}: [#{key}] exists"
rescue
t = Translation.new(key: key, locale: locale)
puts "#{locale}: creating [#{key}]"
end
# The sources contain English strings, no matter what I18n.default_locale is.
t.value = key if locale == :en && t.value.blank?
t.save # If it already existed, a value might have been added.
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment