Create Remote Translations Caller
This module is used in a callback model and in charge of
- extracting resources associated from RemoteTranslation and preparing
its fields to be sent to the MicrosoftTranslateClient thought DelayedJobs
- receive the response from MicrosoftTranslateClient and update resource
with his translates
Co-authored-by: javierm <elretirao@gmail.com>
This commit is contained in:
49
lib/remote_translations_caller.rb
Normal file
49
lib/remote_translations_caller.rb
Normal file
@@ -0,0 +1,49 @@
|
||||
class RemoteTranslationsCaller
|
||||
attr_reader :remote_translation
|
||||
|
||||
def initialize(remote_translation)
|
||||
@remote_translation = remote_translation
|
||||
end
|
||||
|
||||
def call
|
||||
update_resource
|
||||
destroy_remote_translation
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def update_resource
|
||||
Globalize.with_locale(locale) do
|
||||
resource.translated_attribute_names.each_with_index do |field, index|
|
||||
resource.send(:"#{field}=", translations[index])
|
||||
end
|
||||
end
|
||||
resource.save
|
||||
end
|
||||
|
||||
def destroy_remote_translation
|
||||
if resource.valid?
|
||||
remote_translation.destroy
|
||||
else
|
||||
remote_translation.update(error_message: resource.errors.messages)
|
||||
end
|
||||
end
|
||||
|
||||
def resource
|
||||
@resource ||= remote_translation.remote_translatable
|
||||
end
|
||||
|
||||
def translations
|
||||
@translations ||= MicrosoftTranslateClient.new.call(fields_values, locale)
|
||||
end
|
||||
|
||||
def fields_values
|
||||
resource.translated_attribute_names.map do |field|
|
||||
resource.send(field)
|
||||
end
|
||||
end
|
||||
|
||||
def locale
|
||||
remote_translation.locale
|
||||
end
|
||||
end
|
||||
Reference in New Issue
Block a user