require 'rake' module Banyan class Tasks include ::Rake::DSL def initialize define_tasks end def define_tasks namespace :translations do namespace :categories do desc "export data into yml file" task :export, [:full_filename] => :environment do |t, args| args.with_defaults(full_filename: "current_translations.yml") filename = args[:full_filename] || 'current_translations.yml' hash_categorygroup_translations = {} I18n.available_locales.each do |l| cg_translations = Banyan::CategoryGroup::Translation.select('banyan_category_group_id, name').where(locale: l) hash_categorygroup_translations[l.to_s] = cg_translations.each_with_object({}) do |cgt,h| banyan_category_group = Banyan::CategoryGroup.find cgt.banyan_category_group_id h[banyan_category_group.tag] = cgt.name end end hash_category_translations = {} I18n.available_locales.each do |l| cat_translations = Banyan::Category::Translation.select('banyan_category_id, name').where(locale: l) hash_category_translations[l.to_s] = cat_translations.each_with_object({}) do |ct,h| banyan_category = Banyan::Category.find ct.banyan_category_id h[banyan_category.tag] = ct.name end end File.open("#{Rails.root}/#{filename}", 'w') do |file| file.puts({'banyan_category_group_translations' => hash_categorygroup_translations, 'banyan_category_translations' => hash_category_translations }.to_yaml) end end desc "import translations from yml file" task :import, [:full_filename] => :environment do |t, args| args.with_defaults(full_filename: "new_translations.yml") filename = args[:full_filename] || 'new_translations.yml' counter = 0 yf = File.open("#{Rails.root}/#{filename}", "r") ydata = YAML.load_file(yf) ydata.each do |(kind,node)| if kind == 'banyan_category_group_translations' puts I18n.available_locales.inspect I18n.available_locales.each do |l| if node[l.to_s] hash = node[l.to_s] hash.each_pair do |key, value| banyan_category_groups = Banyan::CategoryGroup.where(tag: key) banyan_category_groups.each do |banyan_category_group| banyan_category_group_translation = Array(banyan_category_group.translations.find_or_create_by_locale(l)).first if banyan_category_group_translation banyan_category_group_translation.attributes= {name: value} if banyan_category_group_translation.changed? && banyan_category_group_translation.save! counter += 1 end end end end end end elsif kind == 'banyan_category_translations' I18n.available_locales.each do |l| if node[l.to_s] hash = node[l.to_s] hash.each_pair do |key, value| banyan_categories = Banyan::Category.where(tag: key) banyan_categories.each do |banyan_category| banyan_category_translation = Array(banyan_category.translations.find_or_create_by_locale(l)).first if banyan_category_translation banyan_category_translation.attributes = {name: value} if banyan_category_translation.changed? && banyan_category_translation.save! counter += 1 end end end end end end end end puts "Updated #{counter} translations" end end end end end end