Created
October 22, 2015 07:35
-
-
Save wteuber/10809df69f88e908fdc5 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
#!/usr/bin/env ruby | |
require 'yaml' | |
require 'active_support/all' | |
class Hash | |
def to_hash_recursive | |
result = self.to_hash | |
result.each do |key, value| | |
case value | |
when Hash | |
result[key] = value.to_hash_recursive | |
when Array | |
result[key] = value.to_hash_recursive | |
end | |
end | |
result | |
end | |
def sort_by_key(recursive = false, &block) | |
self.keys.sort(&block).reduce({}) do |seed, key| | |
seed[key] = self[key] | |
if recursive && seed[key].is_a?(Hash) | |
seed[key] = seed[key].sort_by_key(true, &block) | |
end | |
seed | |
end | |
end | |
end | |
class Array | |
def to_hash_recursive | |
result = self | |
result.each_with_index do |value,i| | |
case value | |
when Hash | |
result[i] = value.to_hash_recursive | |
when Array | |
result[i] = value.to_hash_recursive | |
end | |
end | |
result | |
end | |
end | |
file = ARGV[0] | |
if File.exists?(file) | |
yaml = YAML.load_file(file) | |
File.open(file, "w", encoding: "utf-8") do |f| | |
# Rails | |
# I18n.backend.load_translations | |
# default_locale_translations = I18n.backend.send(:translations)[locale].with_indifferent_access.to_hash_recursive | |
# i18n_yaml = {locale.to_s => default_locale_translations}.sort_by_key(true).to_yaml | |
# sort alphabetically: | |
i18n_yaml = yaml.with_indifferent_access.to_hash_recursive.sort_by_key(true).to_yaml | |
process = i18n_yaml.split(/\n/).reject{|e| e == ''}[1..-1] # remove "---" from first line in yaml | |
# add an empty line if yaml tree level changes by 2 or more | |
tmp_ary = [] | |
process.each_with_index do |line, idx| | |
tmp_ary << line | |
unless process[idx+1].nil? | |
this_line_spcs = line.match(/\A\s*/)[0].length | |
next_line_spcs = process[idx+1].match(/\A\s*/)[0].length | |
tmp_ary << '' if next_line_spcs - this_line_spcs < -2 | |
end | |
end | |
output = tmp_ary * "\n" | |
f.puts output | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment