From 5be3ffe15ab5ee5093ed10e2f0fa3576708412fc Mon Sep 17 00:00:00 2001 From: Igor Nemilentsev Date: Tue, 14 May 2024 12:54:04 +0300 Subject: [PATCH] Translator initializer. Added options --- pkg/translator/linguleo.go | 30 +++++++++++++++++++++--------- pkg/translator/options.go | 31 +++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 9 deletions(-) create mode 100644 pkg/translator/options.go diff --git a/pkg/translator/linguleo.go b/pkg/translator/linguleo.go index 3c9b128..fab5550 100644 --- a/pkg/translator/linguleo.go +++ b/pkg/translator/linguleo.go @@ -68,7 +68,7 @@ type Lingualeo struct { } // New initialize lingualeo client -func New(version string) (Lingualeo, error) { +func New(version string, options ...Option) (Lingualeo, error) { client, err := prepareArgs(version) if err != nil { return client, err @@ -82,8 +82,7 @@ func New(version string) (Lingualeo, error) { return client, err } client.mergeConfigs(configArgs) - err = client.checkArgs() - if err != nil { + if err = client.checkArgs(); err != nil { return client, err } if client.Debug { @@ -96,13 +95,26 @@ func New(version string) (Lingualeo, error) { } logger.Prepare(level) client.checkMediaPlayer() - client.Translator, err = api.New(client.Email, client.Password, client.Debug) - if err != nil { - return client, err + + for _, option := range options { + if err = option(&client); err != nil { + return client, err + } + } + if client.Translator == nil { + if client.Translator, err = api.New(client.Email, client.Password, client.Debug); err != nil { + return client, err + } + } + if client.Pronouncer == nil { + client.Pronouncer = player.New(client.Player) + } + if client.Downloader == nil { + client.Downloader = files.New() + } + if client.Visualizer == nil { + client.Visualizer = browser.New() } - client.Pronouncer = player.New(client.Player) - client.Downloader = files.New() - client.Visualizer = browser.New() return client, nil } diff --git a/pkg/translator/options.go b/pkg/translator/options.go new file mode 100644 index 0000000..a4367dc --- /dev/null +++ b/pkg/translator/options.go @@ -0,0 +1,31 @@ +package translator + +type Option func(*Lingualeo) error + +func WithTranslator(t Translator) Option { + return func(l *Lingualeo) error { + l.Translator = t + return nil + } +} + +func WithVisualizer(v Visualizer) Option { + return func(l *Lingualeo) error { + l.Visualizer = v + return nil + } +} + +func WithDownloader(d Downloader) Option { + return func(l *Lingualeo) error { + l.Downloader = d + return nil + } +} + +func WithPronouncer(p Pronouncer) Option { + return func(l *Lingualeo) error { + l.Pronouncer = p + return nil + } +}