Allow Locale backends to work with different Translator sources using AddTranslator method for Locale object. Fixes #22

This commit is contained in:
Leonel Quinteros
2018-07-05 11:37:25 -03:00
parent 431a313411
commit 8e9d9df2e2
2 changed files with 44 additions and 10 deletions

View File

@@ -59,7 +59,7 @@ type Locale struct {
}
// NewLocale creates and initializes a new Locale object for a given language.
// It receives a path for the i18n files directory (p) and a language code to use (l).
// It receives a path for the i18n .po/.mo files directory (p) and a language code to use (l).
func NewLocale(p, l string) *Locale {
return &Locale{
path: p,
@@ -133,6 +133,21 @@ func (l *Locale) AddDomain(dom string) {
l.Unlock()
}
// AddTranslator takes a domain name and a Translator object to make it available in the Locale object.
func (l *Locale) AddTranslator(dom string, tr Translator) {
l.Lock()
if l.Domains == nil {
l.Domains = make(map[string]Translator)
}
if l.defaultDomain == "" {
l.defaultDomain = dom
}
l.Domains[dom] = tr
l.Unlock()
}
// GetDomain is the domain getter for the package configuration
func (l *Locale) GetDomain() string {
l.RLock()
@@ -141,8 +156,7 @@ func (l *Locale) GetDomain() string {
return dom
}
// SetDomain sets the name for the domain to be used at package level.
// It reloads the corresponding Translation file.
// SetDomain sets the name for the domain to be used.
func (l *Locale) SetDomain(dom string) {
l.Lock()
l.defaultDomain = dom

View File

@@ -270,8 +270,6 @@ msgstr "More Translation"
t.Errorf("Expected 'Plural index' but got '%s'", tr)
}
// Create Locale with full language code
l = NewLocale("/tmp", "golem")
@@ -298,8 +296,6 @@ msgstr "More Translation"
t.Errorf("Expected 'Plural index' but got '%s'", tr)
}
// Create Locale with full language code
l = NewLocale("fixtures/", "fr_FR")
@@ -352,7 +348,6 @@ msgstr "More Translation"
t.Errorf("Expected 'Plural index' but got '%s'", tr)
}
// Create Locale with full language code
l = NewLocale("fixtures/", "de_AT")
@@ -425,7 +420,7 @@ msgstr[2] "And this is the second plural form: %s"
t.Fatalf("Can't write to test file: %s", err.Error())
}
// Create Locale with full language code
// Create Locale
l := NewLocale("/tmp", "es")
// Init sync channels
@@ -451,3 +446,28 @@ msgstr[2] "And this is the second plural form: %s"
<-ac
<-rc
}
func TestAddTranslator(t *testing.T) {
// Create po object
po := new(Po)
// Parse file
po.ParseFile("fixtures/en_US/default.po")
// Create Locale
l := NewLocale("", "en")
// Add PO Translator to Locale object
l.AddTranslator("default", po)
// Test translations
tr := l.Get("My text")
if tr != "Translated text" {
t.Errorf("Expected 'Translated text' but got '%s'", tr)
}
// Test translations
tr = l.Get("language")
if tr != "en_US" {
t.Errorf("Expected 'en_US' but got '%s'", tr)
}
}