Module: AbAdmin::Models::Locator::ClassMethods

Defined in:
lib/ab_admin/models/locator.rb

Instance Method Summary collapse

Instance Method Details

#export_csv(*keys, locales: nil) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/ab_admin/models/locator.rb', line 32

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

#find_filesObject



16
17
18
# File 'lib/ab_admin/models/locator.rb', line 16

def find_files
  Dir[Rails.root.join('config', 'locales', '*.yml')]
end

#import_csv(csv, locales: nil) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/ab_admin/models/locator.rb', line 46

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

#prepare_data(path) ⇒ Object



25
26
27
28
29
30
# File 'lib/ab_admin/models/locator.rb', line 25

def prepare_data(path)
  data = YAML.load_file(path)
  locale = data.keys.first
  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

#save(path, data) ⇒ Object



20
21
22
23
# File 'lib/ab_admin/models/locator.rb', line 20

def save(path, data)
  data.deep_transform_values! { |v| AbAdmin.normalize_html(v) }
  File.write path, data.deep_stringify_keys.to_yaml.sub(/\A---\s+/, '').gsub(/:\s+$/, ':').gsub(/^(\s+)(yes|no):/, '\1"\2":')
end

#translationsObject



64
65
66
# File 'lib/ab_admin/models/locator.rb', line 64

def translations
  @translations ||= I18n.backend.send(:translations).slice(*I18n.available_locales).transform_values{|v| v.flatten_hash.transform_keys{|k| k.join('.') } }
end