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

并像这样使用它:CCD_ 1。这将翻译属性,并将翻译后的属性保存到en语言的数据库中。

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

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

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

也许它可以变得更干净。。。但它正在发挥作用:)

最新更新