I've been trying to sort an i18n translations YAML file with Ruby so I can manage new translations in a better and organized way, but I've been wondering if there is something to ease the task.
I found a YAML file writer so I can write a hash into a file, but my problem is to sort the hash correctly. If I got hash h
, h.sort
returns an array and I still haven't figured a simple way to do that.
I have YAML files like this:
pt-br:
global:
misc:
total: "Total"
all: "Todos"
close: "Fechar"
cancel: "Cancelar"
crud:
access: "Acessar"
back: "Voltar"
edit: "Editar"
confirm: "Confirmar"
send: "Enviar"
...
(The files are way larger than this)
But I want to sort them this way:
pt-br:
global:
crud:
access: "Acessar"
back: "Voltar"
confirm: "Confirmar"
edit: "Editar"
send: "Enviar"
misc:
all: "Todos"
cancel: "Cancelar"
close: "Fechar"
total: "Total"
I thought that some simple recursive method could help me like this:
def translation_sort(h)
if h.class == Hash
h = h.sort
h.each{|item| translation_sort(item)}
end
h
end
require "yaml"
h=YAML.load_file(File.open("~/pt-br.sample.yml"))
translation_sort(h)