feat(time): use locale word fallback for relative time
Co-Authored-By: Virgil <virgil@lethean.io>
This commit is contained in:
parent
8a23f26a47
commit
e28a86d705
2 changed files with 35 additions and 1 deletions
11
time.go
11
time.go
|
|
@ -48,11 +48,20 @@ func FormatAgo(count int, unit string) string {
|
|||
key := "time.ago." + unit
|
||||
result := svc.T(key, map[string]any{"Count": count})
|
||||
if result == key {
|
||||
return core.Sprintf("%d %s ago", count, Pluralize(unit, count))
|
||||
return core.Sprintf("%d %s ago", count, fallbackAgoUnit(unit, count))
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func fallbackAgoUnit(unit string, count int) string {
|
||||
lang := currentLangForGrammar()
|
||||
rendered := renderWord(lang, unit)
|
||||
if rendered != unit {
|
||||
return rendered
|
||||
}
|
||||
return Pluralize(unit, count)
|
||||
}
|
||||
|
||||
func normalizeAgoUnit(unit string) string {
|
||||
unit = core.Lower(core.Trim(unit))
|
||||
switch unit {
|
||||
|
|
|
|||
25
time_test.go
25
time_test.go
|
|
@ -245,3 +245,28 @@ func TestFormatAgo_Good_FrenchRelativeTime(t *testing.T) {
|
|||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFormatAgo_FallsBackToLocaleWordMap(t *testing.T) {
|
||||
prev := Default()
|
||||
svc, err := NewWithFS(fstest.MapFS{
|
||||
"en.json": &fstest.MapFile{
|
||||
Data: []byte(`{
|
||||
"gram": {
|
||||
"word": {
|
||||
"month": "mois"
|
||||
}
|
||||
}
|
||||
}`),
|
||||
},
|
||||
}, ".")
|
||||
require.NoError(t, err)
|
||||
SetDefault(svc)
|
||||
t.Cleanup(func() {
|
||||
SetDefault(prev)
|
||||
})
|
||||
|
||||
require.NoError(t, SetLanguage("en"))
|
||||
|
||||
got := FormatAgo(2, "month")
|
||||
assert.Equal(t, "2 mois ago", got)
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue