tags:

views:

79

answers:

1

I would like to know how to parse a YAML file with the following contents:

--- 
javascripts: 
- fo_global:
  - lazyload-min
  - holla-min

Currently I am trying to parse it this way:

@custom_asset_packages_yml = (File.exists?("#{RAILS_ROOT}/config/asset_packages.yml") ? YAML.load_file("#{RAILS_ROOT}/config/asset_packages.yml") : nil)
    if !@custom_asset_packages_yml.nil?
      @custom_asset_packages_yml['javascripts'].each{ |js|
        js['fo_global'].each{ |script|
         script
        }
      }
    end

But it doesn't seem to work and gives me an error that the value is nil.

You have a nil object when you didn't expect it! You might have expected an instance of Array. The error occurred while evaluating nil.each

If I try this, it puts out the entire string (fo_globallazyload-minholla-min):

if !@custom_asset_packages_yml.nil?
          @custom_asset_packages_yml['javascripts'].each{ |js|
            js['fo_global']
          }
        end

Any ideas would be great! Thanks!

+6  A: 

Maybe I'm missing something, but why try to parse the file? Why not just load the YAML and examine the object(s) that result?

If your sample YAML is in some.yaml, then this:

require 'yaml'
thing = YAML.load_file('some.yml')
puts thing.inspect

gives me

{"javascripts"=>[{"fo_global"=>["lazyload-min", "holla-min"]}]}
Mike Woodhouse
I agree, that's the wonderful about YAML - we can serialize something then read it back in later, so why not use that capability.
Greg
Ah, I was unaware that you could do that with a YAML file. Thanks so much!
alvincrespo