Created
May 29, 2016 23:53
-
-
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.
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 '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