Created
October 26, 2010 11:00
-
-
Save branch14/646703 to your computer and use it in GitHub Desktop.
mass translate active record entries
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coll = Product.find_all_by_kind('material') + | |
# Product.find_all_by_kind('materialgroup') + | |
# Product.find_all_by_kind('pricegroup') + | |
# Product.find_all_by_kind('component') | |
# mass_translate(coll, [:name, :description], :en, :de) | |
# mass_translate(coll, [:name, :description], :de, [:en, :fr]) { |v, l| "#{v} (#{l})" } | |
# | |
# coll = Product.find_all_by_kind('product') | |
# mass_translate(coll, :name, :de, [:en, :fr]) | |
# | |
# coll = Protoype.all + Taxon.all + Taxonomy .all | |
# mass_translate(coll, :name, :en, :de) | |
# mass_translate(coll, :name, :de, [:en, :fr]) { |v, l| "#{t} (#{l})" } | |
# | |
# coll = Property.all | |
# mass_translate(coll, :presentation, :en, :de) | |
# mass_translate(coll, :presentation, :de, [:en, :fr]) { |v, l| "#{v} (#{l})" } | |
# | |
def mass_translate(collection, attributes, from_locale, to_locales) | |
default = I18n.locale | |
attributes = [attributes] unless attributes.is_a? Array | |
to_locales = [to_locales] unless to_locales.is_a? Array | |
collection.each do |object| | |
I18n.locale = from_locale | |
values = Hash.new.tap do |hash| | |
attributes.each do |attribute| | |
hash[attribute] = object.send(attribute) | |
end | |
end | |
attributes.each do |attribute| | |
puts "read (#{from_locale}): #{values[attribute]}" | |
to_locales.each do |to_locale| | |
I18n.locale = to_locale | |
old_value = object.send(attribute) | |
puts "overwrite (#{to_locale}): #{old_value}" unless old_value.nil? | |
new_value = block_given? ? yield(values[attribute], to_locale) : values[attribute] | |
new_value = "random#{Time.now.to_i}-#{rand(1000)}" if new_value.blank? # HACK! | |
puts "write (#{to_locale}): #{new_value}" | |
object.update_attribute(attribute, new_value) | |
end | |
end | |
end | |
I18n.locale = default | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment