Created
June 13, 2012 11:22
-
-
Save dipth/2923522 to your computer and use it in GitHub Desktop.
I18nDbLookup
This file contains 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
class I18nDbLookup < I18n::Backend::Simple | |
def load_translations(*filenames) | |
# First we load the db-translations | |
load_translations_from_db | |
# Then we load the default yml-files | |
super | |
end | |
protected | |
def load_translations_from_db | |
# First we find all the default translations for each language | |
Language.all.each do |l| | |
store_db_translations(l.locale_key, l.translations.where("is_default = true")) | |
end | |
# Then we load the site-specific translations | |
Site.includes(:translations).each do |s| | |
store_db_translations(s.locale, s.translations, "site_#{s.id}") | |
end | |
end | |
def store_db_translations(locale, translations, scope = nil) | |
data = {} | |
translations.each do |t| | |
data[t.key.to_sym] = t.value.to_s | |
end | |
if scope.present? | |
store_translations(locale.to_sym, {scope.to_sym => data}) | |
else | |
store_translations(locale.to_sym, data) | |
end | |
end | |
def lookup(locale, key, scope = [], options = {}) | |
if scope.is_a?(Array) | |
scoped_to_site = scope.find_all { |s| s =~ /site_\d+/ }.any? | |
scope_without_site = scope.reject { |s| s =~ /site_\d+/ } | |
else | |
scoped_to_site = scope =~ /site_\d+/ | |
scope_without_site = "" | |
end | |
# We first check if there is a translation scoped to the site, otherwise | |
# we try the default scope. | |
scoped_to_site ? super || super(locale, key, scope_without_site, options) : super | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment