Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hash inside YAML file?

I want to include a hash and list inside a YAML file that I'm parsing with the following command:

APP_CONFIG = YAML.load_file("#{RAILS_ROOT}/config/config.yml")

My YAML file looks like this:

feeds: [{:url => 'http://www.google.com', :label => 'default'}]

But this doesn't seem to work. How would I go about achieving such a thing?

Thanks, Yuval


EDIT: Sorry, guys. I'm still unclear about how to do this and I suspect it is in part due to my somewhat vague phrasing. I asked a better-phrased, more broad question here. Thank you!

like image 938
Yuval Karmi Avatar asked Jun 13 '10 21:06

Yuval Karmi


People also ask

What is a Hash in Yaml?

For Ansible, nearly every YAML file starts with a list. Each item in the list is a list of key/value pairs, commonly called a “hash” or a “dictionary”.

What does ampersand mean in Yaml?

The & marks an alias for the node (in your example &default aliases the development node as "default") and the * references the aliased node with the name "default". The <<: inserts the content of that node.


2 Answers

You can mark it up like this

feeds:  -    url: 'http://www.google.com'   label: 'default' 

Note the spacing is important here. "-" must be indented by a single space (not a tab), and followed by a single space. And url & label must be indented by two spaces (not tabs either).

Additionally this might be helpful: http://www.yaml.org/YAML_for_ruby.html

like image 99
Ceilingfish Avatar answered Sep 25 '22 07:09

Ceilingfish


Ceilingfish's answer is maybe technically correct, but he recommends to use a white space at the end of a line. This is prone to errors and is not a good practice!

This is how I would do it:

Create a settings.yaml file with the following contents:

---
feeds:
  :url: 'http://www.google.com'
  :label: 'default'

This will create the following hash after the YAML file has been loaded:

irb(main):001:0> require 'yaml'
=> true
irb(main):002:0> YAML.load_file('settings.yaml')
=> {"feeds"=>{:url=>"http://www.google.com", :label=>"default"}}
irb(main):003:0> 

In this example, I also use symbols since this seems to be the preferred way of storing Ruby keys in Ruby.

like image 38
jpoppe Avatar answered Sep 23 '22 07:09

jpoppe