require "i18n_screwdriver/version" require "i18n_screwdriver/translation" require "i18n_screwdriver/translation_helper" require "i18n_screwdriver/rails" module I18nScrewdriver Error = Class.new(StandardError) class << self attr_accessor :excluded_paths, :included_gems end self.excluded_paths = [%r{/tmp/}, %r{/node_modules/}, %r{/packs/}, %r{/packs-test}] self.included_gems = [] def self.filename_for_locale(locale) File.join("config", "locales", "application.#{locale}.yml") end def self.generate_key(source) return ":#{source}" if source.is_a?(Symbol) source = source.strip (source =~ /^:[a-z][a-z0-9_]*$/) ? source : Digest::MD5.hexdigest(source) end def self.file_with_translations_exists?(locale) File.exists?(filename_for_locale(locale)) end def self.load_translations(locale) path = filename_for_locale(locale) raise Error, "File #{path} not found!" unless File.exists?(path) sanitize_hash(YAML.load_file(path)[locale]) end def self.write_translations(locale, translations) File.open(filename_for_locale(locale), "w") do |file| file.puts "# use rake task i18n:update to generate this file" file.puts file.puts({locale => in_utf8(translations)}.to_yaml(:line_width => -1)) file.puts end end def self.grab_texts_to_be_translated(string) [].tap do |texts| texts.concat(string.scan(/_\((? 0 I18n.available_locales.map(&:to_s) end end def self.update_translations_file(locale, translations) existing_translations = file_with_translations_exists?(locale) ? load_translations(locale) : {} existing_translations.select!{ |k| translations.has_key?(k) } translations.each do |k, v| next if existing_translations[k] existing_translations[k] = (default_locale == locale) ? v : nil end write_translations(locale, existing_translations) end def self.sanitize_hash(hash) {}.tap do |new_hash| hash.each{ |k, v| new_hash[k.to_s] = v.to_s } end end def self.translate(string, **options) I18n.translate!(generate_key(string), **options) rescue I18n::MissingTranslationData I18n.translate(string, **options) end def self.extract_text(string) namespace, text = string.split("|", 2) text ? text : namespace end end