Guest User

Untitled

a guest
Jun 19th, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.75 KB | None | 0 0
  1. # coll = Product.find_all_by_kind('material') +
  2. # Product.find_all_by_kind('materialgroup') +
  3. # Product.find_all_by_kind('pricegroup') +
  4. # Product.find_all_by_kind('component')
  5. # mass_translate(coll, [:name, :description], :en, :de)
  6. # mass_translate(coll, [:name, :description], :de, [:en, :fr]) { |v, l| "#{v} (#{l})" }
  7. #
  8. # coll = Product.find_all_by_kind('product')
  9. # mass_translate(coll, :name, :de, [:en, :fr])
  10. #
  11. # coll = Protoype.all + Taxon.all + Taxonomy .all
  12. # mass_translate(coll, :name, :en, :de)
  13. # mass_translate(coll, :name, :de, [:en, :fr]) { |v, l| "#{t} (#{l})" }
  14. #
  15. # coll = Property.all
  16. # mass_translate(coll, :presentation, :en, :de)
  17. # mass_translate(coll, :presentation, :de, [:en, :fr]) { |v, l| "#{v} (#{l})" }
  18. #
  19. def mass_translate(collection, attributes, from_locale, to_locales)
  20. default = I18n.locale
  21. attributes = [attributes] unless attributes.is_a? Array
  22. to_locales = [to_locales] unless to_locales.is_a? Array
  23. collection.each do |object|
  24. I18n.locale = from_locale
  25. values = Hash.new.tap do |hash|
  26. attributes.each do |attribute|
  27. hash[attribute] = object.send(attribute)
  28. end
  29. end
  30. attributes.each do |attribute|
  31. puts "read (#{from_locale}): #{values[attribute]}"
  32. to_locales.each do |to_locale|
  33. I18n.locale = to_locale
  34. old_value = object.send(attribute)
  35. puts "overwrite (#{to_locale}): #{old_value}" unless old_value.nil?
  36. new_value = block_given? ? yield(values[attribute], to_locale) : values[attribute]
  37. new_value = "random#{Time.now.to_i}-#{rand(1000)}" if new_value.blank? # HACK!
  38. puts "write (#{to_locale}): #{new_value}"
  39. object.update_attribute(attribute, new_value)
  40. end
  41. end
  42. end
  43. I18n.locale = default
  44. end
Add Comment
Please, Sign In to add comment