Move remote translations controller methods to the model

Now that all the code related to this model is in the same place,
changing it will be easier.
This commit is contained in:
Javi Martín
2023-01-29 16:47:52 +01:00
parent d09a47a023
commit 26cc75a891
2 changed files with 12 additions and 19 deletions

View File

@@ -2,34 +2,21 @@ class RemoteTranslationsController < ApplicationController
skip_authorization_check skip_authorization_check
respond_to :html, :js respond_to :html, :js
before_action :set_remote_translations, only: :create
def create def create
@remote_translations.each do |remote_translation| RemoteTranslation.create_all(remote_translations_params)
RemoteTranslation.create!(remote_translation) unless translations_enqueued?(remote_translation)
end
redirect_to request.referer, notice: t("remote_translations.create.enqueue_remote_translation") redirect_to request.referer, notice: t("remote_translations.create.enqueue_remote_translation")
end end
private private
def remote_translations_params def remote_translations_params
params.permit(allowed_params) ActiveSupport::JSON.decode(params["remote_translations"]).map do |remote_translation_params|
remote_translation_params.slice(*allowed_params)
end
end end
def allowed_params def allowed_params
[:remote_translations] ["remote_translatable_id", "remote_translatable_type", "locale"]
end
def set_remote_translations
remote_translations = remote_translations_params["remote_translations"]
decoded_remote_translations = ActiveSupport::JSON.decode(remote_translations)
@remote_translations = decoded_remote_translations.map do |remote_translation|
remote_translation.slice("remote_translatable_id", "remote_translatable_type", "locale")
end
end
def translations_enqueued?(remote_translation)
RemoteTranslation.remote_translation_enqueued?(remote_translation)
end end
end end

View File

@@ -41,6 +41,12 @@ class RemoteTranslation < ApplicationRecord
resource.class.translates? && resource.translations.where(locale: I18n.locale).empty? resource.class.translates? && resource.translations.where(locale: I18n.locale).empty?
end end
def self.create_all(remote_translations_params)
remote_translations_params.each do |remote_translation_params|
create!(remote_translation_params) unless remote_translation_enqueued?(remote_translation_params)
end
end
def already_translated_resource def already_translated_resource
if remote_translatable&.translations&.where(locale: locale).present? if remote_translatable&.translations&.where(locale: locale).present?
errors.add(:locale, :already_translated) errors.add(:locale, :already_translated)