lib/ab_admin/models/locator.rb in ab_admin-0.7.0 vs lib/ab_admin/models/locator.rb in ab_admin-0.8.0
- old
+ new
@@ -1,5 +1,7 @@
+require 'csv'
+
module AbAdmin
module Models
module Locator
extend ActiveSupport::Concern
@@ -21,16 +23,47 @@
end
def prepare_data(path)
data = YAML.load_file(path)
locale = data.keys.first
- OpenStruct.new({locale: locale.to_sym, data: data[locale], flat_data: flat_hash(data[locale]),
+ OpenStruct.new({locale: locale.to_sym, data: data[locale], flat_data: data[locale].flatten_hash,
filename: File.basename(path), path: path, dir: File.dirname(path)})
end
- def flat_hash(hash, k = [])
- return {k => hash} unless hash.is_a?(Hash)
- hash.inject({}) { |h, v| h.merge! flat_hash(v[-1], k + [v[0]]) }
+ def export_csv(*keys, locales: nil)
+ return if keys.blank?
+ locales ||= I18n.available_locales
+ I18n.backend.available_locales # Force load translations
+ filter_keys = keys.map {|k| k.include?('*') ? Regexp.new("\\A#{k.gsub('.', '\.').gsub('*', '.*')}\\z") : k}
+ data = filter_keys.each_with_object(Hash.new { |h, k| h[k] = [] }) do |key, res|
+ locales.each_with_index do |l, i|
+ translations[l].find_all{|k, _| key.is_a?(Regexp) ? k =~ key : k == key }.each{|k, v| res[k][i] = v}
+ end
+ end
+ for_csv = [['DO NOT EDIT THIS COLUMN!', *locales]] + data.map{|k, v| [k, *v] }
+ for_csv.map(&:to_csv).join
+ end
+
+ def import_csv(csv, locales: nil)
+ return if csv.blank?
+ locales ||= I18n.available_locales
+ csv_data = CSV.parse(csv)
+ csv_data.shift.each_with_index do |l, i|
+ next if i.zero? || !locales.include?(l.to_sym)
+ path = Rails.root.join('config', 'locales', "#{l}.yml")
+ raise "Missing file #{path}" unless File.file?(path)
+ data = YAML.load_file(path)
+ csv_data.each do |d|
+ key_parts = [l.to_s] + d[0].split('.')
+ raise "Invalid key #{d[0]}" unless data.dig(*key_parts)
+ data.store_multi(d[i], *key_parts)
+ end
+ save path, data
+ end
+ end
+
+ def translations
+ @translations ||= I18n.backend.send(:translations).slice(*I18n.available_locales).transform_values{|v| v.flatten_hash.transform_keys{|k| k.join('.') } }
end
end
def initialize
@data = {}
\ No newline at end of file