How can I sort YAML files?

前端 未结 9 961
灰色年华
灰色年华 2021-02-02 12:55

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

9条回答
  •  名媛妹妹
    2021-02-02 13:00

    Here's another alternative for anyone else who comes across this..

    require 'yaml'
    
    yaml = YAML.load(IO.read(File.join(File.dirname(__FILE__), 'example.yml')))
    
    @yml_string = "---\n"
    
    def recursive_hash_to_yml_string(hash, depth=0)
      spacer = ""
      depth.times { spacer += "  "}
      hash.keys.sort.each do |sorted_key|
        @yml_string += spacer + sorted_key + ": "
        if hash[sorted_key].is_a?(Hash)
          @yml_string += "\n"
          recursive_hash_to_yml_string(hash[sorted_key], depth+1)
        else
          @yml_string += "#{hash[sorted_key].to_s}\n"
        end
      end
    end
    
    recursive_hash_to_yml_string(yaml)
    
    open(File.join(File.dirname(__FILE__), 'example.yml'), 'w') { |f|
      f.write @yml_string
    }
    

提交回复
热议问题