You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

81 lines
1.5KB

  1. package translation
  2. import (
  3. "fmt"
  4. "gitoa.ru/go-4devs/translation/arg"
  5. "golang.org/x/text/language"
  6. )
  7. // Option configures translate.
  8. type Option func(*Translate)
  9. // Translate configure translate.
  10. type Translate struct {
  11. Domain string
  12. Locale language.Tag
  13. Args []Arg
  14. }
  15. // ArgValues gets value arguments.
  16. func (t *Translate) ArgValues() []interface{} {
  17. a := make([]interface{}, len(t.Args))
  18. for i, v := range t.Args {
  19. a[i] = v.Val()
  20. }
  21. return a
  22. }
  23. // Arg arg translate.
  24. type Arg interface {
  25. Val() interface{}
  26. fmt.Stringer
  27. }
  28. // WithNumber sets number with options.
  29. func WithNumber(key string, val interface{}, opts ...arg.NumberOption) Option {
  30. return func(t *Translate) {
  31. t.Args = append(t.Args, arg.Number{Key: key, Value: val}.Configure(opts...))
  32. }
  33. }
  34. // WithCurrency sets date argument.
  35. func WithCurrency(key string, val interface{}, opts ...arg.CurrencyOption) Option {
  36. return func(t *Translate) {
  37. c := arg.Currency{Value: val, Key: key}
  38. for _, o := range opts {
  39. o(&c)
  40. }
  41. t.Args = append(t.Args, c)
  42. }
  43. }
  44. // WithDomain sets domain translate.
  45. func WithDomain(domain string) Option {
  46. return func(o *Translate) {
  47. o.Domain = domain
  48. }
  49. }
  50. // WithLocale sets locale translate.
  51. func WithLocale(locale string) Option {
  52. return func(o *Translate) {
  53. o.Locale = language.Make(locale)
  54. }
  55. }
  56. // WithArgs sets arguments value.
  57. func WithArgs(vals ...interface{}) Option {
  58. return func(t *Translate) {
  59. args := make([]Arg, len(vals))
  60. for i, val := range vals {
  61. args[i] = arg.Arg{Value: val}
  62. }
  63. t.Args = append(t.Args, args...)
  64. }
  65. }