【问题标题】:rails - How to refactor this methodrails - 如何重构此方法
【发布时间】:2021-10-21 23:55:53
【问题描述】:

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

我有一些工作,但我想对其进行重构,使其更加通用:

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-rails activemodel


    【解决方案1】:

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

    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
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-11
      • 1970-01-01
      • 1970-01-01
      • 2015-03-20
      • 1970-01-01
      • 2010-11-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多