A simple YAML sorter

When you have a lot of locale files in a rails app you might want to keep the keys sorted alphabetically. Here is a quick Ruby object and rake task for that.

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

Rake task that updates the files in place. Make sure you have a backup of the originals!

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