Last active
August 30, 2022 10:23
-
-
Save amicojeko/0ff7c9990afe605eb7e882d1d1701fc4 to your computer and use it in GitHub Desktop.
YAML Sorter
This file contains 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
# 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 |
This file contains 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
# 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