Skip to content

Instantly share code, notes, and snippets.

@amicojeko
Last active August 30, 2022 10:23
Show Gist options
  • Save amicojeko/0ff7c9990afe605eb7e882d1d1701fc4 to your computer and use it in GitHub Desktop.
Save amicojeko/0ff7c9990afe605eb7e882d1d1701fc4 to your computer and use it in GitHub Desktop.
YAML Sorter
# Code by PZac
require 'yaml_sorter'
namespace :yaml do
task :fix_all do
Dir.glob('config/locales/**/*.yml').each do |f|
YamlSorter.new(f).fix!
end
end
task :sort do
YamlSorter.new(ENV['FILE']).fix!
end
end
# Code by PZac
class YamlSorter
def initialize(filename)
@filename = filename
end
def data
YAML.load_file(@filename)
end
def recursive_sort(data)
case data
when Array
data.map{recursive_sort(_1)}
when Hash
{}.tap do |hash|
data.sort.each do |(key, val)|
hash[key] = recursive_sort(val)
end
end
else
data
end
end
def dump
YAML.dump(recursive_sort(data))
end
def fix!
data = dump
File.open(@filename, 'w') do |f|
f.puts(data)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment