Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading and generating Yaml file with similar keys

I've got a yaml file document which have similar keys :-

sample_file.yml

line:
  title: line-name
  department: transcription

  input_formats:
    - input_format:
        name: company
        required: true
        valid_type: general
    - input_format:
        name: website
        required: false
        valid_type: url

After generating new_file.yml the keys get sorted in alphabetical order :-

new_file.yml

line: 
  department: transcription
  input_formats: 
    - 
      input_format: 
      name: company
      required: true
      valid_type: general
    - 
      input_format: 
      name: website
      required: false
      valid_type: url

  title: line-name

the code for opening sample_file and making new_file is below :-

require 'yaml'
require 'ya2yaml'


@file = YAML::load(File.open("/Users/manish/Desktop/yaml/sample_file.yml"))
@new_file = File.new("/Users/manish/Desktop/yaml/new_file.yml", "w+") 
@new_file.syswrite(@file.ya2yaml(:hash_order => ['title','department','input_formats']))

I'm using "ya2yaml" gem for generating yaml file. In order to get the same order as it's in sample_file.yml i've used hash_order here @new_file.syswrite(@file.ya2yaml(:hash_order => ['title','department','input_formats'])), but it's not working. How can i retain the order?

like image 670
Manish Das Avatar asked Jun 16 '11 12:06

Manish Das


2 Answers

Finally i got the solution of the ordering issue.

The :hash_order only work for top level hash.
so it works only when i remove "line" key from my sample_file.yml. Then the order is preserved. :-

title: line-name
department: transcription

input_formats:
  - input_format:
      name: company
      required: true
      valid_type: general
  - input_format:
      name: website
      required: false
      valid_type: url
like image 63
Manish Das Avatar answered Nov 15 '22 21:11

Manish Das


Can you change the format of the YAML file? Your YAML file specifies a hash with duplicate keys. That's a no-no.

If instead the YAML file used a list, like this:

line:
    title: line-name
    department: transcription

    formats:
        - input_format:
          name: company
          required: true
          valid_type: general

        - input_format:
          name: website
          required: false
          valid_type: url
....

Those extra dashes would solve your problem for you.

like image 21
Andy Avatar answered Nov 15 '22 20:11

Andy