ruby-on-rails - 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
语言保存到数据库中。
提前感谢任何可以为我指明有效方向的人。
解决方案
好的,我实际上设法为活动记录创建了一个自动翻译方法:
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
也许它可以变得更清洁......但它正在工作:)
推荐阅读
- apache-spark - 是否可以在同一个 Spark 会话中将两个不同的 csv 文件作为两个结构化流(两个表)加载
- html-framework-7 - 如何在 app.request 中显示预加载器以获取自动完成元素?
- tensorflow - 噪声向量的输入形状如何影响 GAN 中的生成器?
- c++ - 与stitching_detailed.cpp opencv有关的问题
- .net - 应用程序被 Microsoft AV 标记为病毒 - 不确定它发现可疑行为或尝试将其删除的方法
- json - 在 Dart 中将现有字符串转换为原始字符串
- java - XSD 到 Java 类 - 解析模式问题
- google-maps - Anylogic GIS 功能
- r - dplyr 中的标准化结果不一致
- android - 如何通过特定 IP 路由 API 请求?