首页 > 解决方案 > rails - 如何重构此方法

问题描述

我遇到了一点挑战,但我不知道从哪里开始。长话短说,我正在尝试制作一种方法,可以通过 Deepl 或谷歌翻译自动翻译其模型中的记录。

我有一些工作,但我想重构它,让它变得更加通用:

def translate
  texts = [self.title_fr, self.desc_fr, self.descRequirements_fr, self.descTarget_fr, self.descMeet_fr, self.descAdditional_fr]
  
  translations = DeepL.translate texts, 'FR', 'EN'

  self.update(title_en: translations[0], descRequirements_en: translations[2], descTarget_en: translations[3], descMeet_en: translations[4], descAdditional_en: translations[5])
end

希望这是不言自明的。

我希望有一个方法/关注像这样工作:

def deeplTranslate(record, attributes)
  // Code to figure out
end

并像这样使用它:deeplTranslate(post, ['title', 'desc', 'attribute3'])。这将翻译属性并将翻译后的属性以en语言保存到数据库中。

提前感谢任何可以为我指明有效方向的人。

标签: ruby-on-railsactivemodel

解决方案


好的,我实际上设法为活动记录创建了一个自动翻译方法:

def deeplTranslate(record, attributes, originLang, newLang)
  keys = attributes.map{|a| record.instance_eval(a + "_#{originLang}")}
  
  translations = DeepL.translate keys, originLang, newLang

  new_attributes = Hash.new
  attributes.each_with_index do |a, i|
    new_attributes[a + "_#{newLang}"] = translations[i].text
  end

  record.update(new_attributes)
end

也许它可以变得更清洁......但它正在工作:)


推荐阅读