Reputation: 97
I got a little bit of a challenge but I don't know where to start. Long story short, I'm trying to make a method that will automatically translate a record from its model via Deepl or Google Translate.
I've got something working but I want to refactor it so it gets more versatile:
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
Hopefully this is self explanatory.
I would love to have a method/concern working like such :
def deeplTranslate(record, attributes)
// Code to figure out
end
and use it like such : deeplTranslate(post, ['title', 'desc', 'attribute3'])
. And that will translate the attributes and save the translated attributes to the database in en
language.
Thanks in advance to anyone that can point me to a valid direction to go towards.
Upvotes: 0
Views: 47
Reputation: 97
Okay, I actually managed to create an auto translate method for active record :
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
Maybe it can get cleaner... But it's working : )
Upvotes: 1