¿Cómo analizo un archivo YAML?
Me gustaría saber cómo analizar un archivo YAML con el siguiente contenido:
---
javascripts:
- fo_global:
- lazyload-min
- holla-min
Actualmente estoy tratando de analizarlo de esta manera:
@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
Pero no parece funcionar y me da un error que el valor es 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
Si intento esto, se pone toda la cadena (fo_globallazyload-minholla-min):
if !@custom_asset_packages_yml.nil?
@custom_asset_packages_yml['javascripts'].each{ |js|
js['fo_global']
}
end
175
Author: the Tin Man, 2010-10-07
2 answers
Tal vez me falta algo, pero ¿por qué tratar de analizar el archivo? ¿Por qué no simplemente cargar el YAML y examinar los objetos que resultan?
Si su YAML de muestra está en some.yml
, entonces esto:
require 'yaml'
thing = YAML.load_file('some.yml')
puts thing.inspect
Me da
{"javascripts"=>[{"fo_global"=>["lazyload-min", "holla-min"]}]}
402
Author: Mike Woodhouse,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-11-07 05:32:16
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-11-07 05:32:16
Tuve el mismo problema, pero también quería obtener el contenido del archivo (después del front-matter YAML).
Esta es la mejor solución que he encontrado:
if (md = contents.match(/^(?<metadata>---\s*\n.*?\n?)^(---\s*$\n?)/m))
self.contents = md.post_match
self.metadata = YAML.load(md[:metadata])
end
Fuente y discusión: https://practicingruby.com/articles/tricks-for-working-with-text-and-files
10
Author: sarfata,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-10-05 09:48:54
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-10-05 09:48:54