Skip to content

Instantly share code, notes, and snippets.

@tejo
Created January 11, 2012 08:56
Show Gist options
  • Select an option

  • Save tejo/1593793 to your computer and use it in GitHub Desktop.

Select an option

Save tejo/1593793 to your computer and use it in GitHub Desktop.
require 'csv'
namespace :locale do
namespace :translations do
desc 'export translations'
task :export => :environment do
params_check
locale = ENV['locale'].to_sym
model = translate_model
columns = model.columns_hash.select {|k,v| v.type == :string || v.type == :text || v.type == :integer }.keys - ['id']
CSV.open("#{Rails.root}/vendor/data/translations/#{ENV['model']}.#{locale}.csv", "wb") do |csv|
csv << columns
model.where(:locale => locale).each do |m|
row = []
columns.each do |attribute|
row << m.send(attribute)
end
csv << row
end
end
end
desc 'delete translations'
task :delete => :environment do
params_check
model = translate_model
locale = ENV['locale'].to_sym
model.delete_all(:locale => locale)
end
desc 'import translations'
task :import => :environment do
params_check
model = translate_model
locale = ENV['locale'].to_sym
db = []
CSV.foreach("#{Rails.root}/vendor/data/translations/#{ENV['model']}.#{locale}.csv") do |r|
db << r
end
columns = db.delete_at(0)
db.each_with_index do |row|
translation = model.new
columns.each do |attribute|
data = row[columns.index(attribute)]
translation.send("#{attribute}=", data) if data
end
translation.save
end
end
end
end
def params_check
if ENV['locale'].nil? || ENV['model'].nil?
puts 'please specify locale and model eg: locale=en model=product'
exit
end
end
def translate_model
begin
model = (ENV['model'].singularize+'_translation').camelize.constantize
rescue
puts "#{ENV['model']} translations not found"
exit
end
model
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment