:: Web Design, Ruby on Rails, JavaScript, Photography, and more ::

Tuesday, March 31, 2009

Ruby YAML config files - hash key confusion

If you have played around with YAML files in Rails at all, you may have run across a confusing issue: often times in Rails, hashes are accessed via either a string or symbol but if you load up a YAML file, the hash can only be accessed by string!
The reason is Rails has a "HashWithIndifferentAccess" object type, that is built on top of the standard ruby Hash, and YAML files by default use the standard ruby hash.
E.g.
h = { :msg => 'Hello World', :date => Time.now }
puts h[:msg] # Hello World
puts h['msg'] # nil

h = HashWithIndifferentAccess.new( { :msg => 'Hello World', :date => Time.now } )
puts h[:msg] # Hello World
puts h['msg'] # Hello World


You can get the indifferenct access behavior in YAML files by putting this at the top of your YAML file:

--- !map:HashWithIndifferentAccess


That is the most flexible way to create your YAML files. If you strictly want symbol access only, you can also prefix each key in your YAML file with a colon:

config.yml
development:
:key_that_is_a_symbol: value 1
key_that_is_NOT_a_symbol: value 2


Once loaded, you will get this behavior:

config = YAML::load_file( 'config.yml' )['development']
puts config[:key_that_is_a_symbol] # value 1
puts config[:key_that_is_NOT_a_symbol] # nil
puts config['key_that_is_a_symbol'] # nil
puts config['key_that_is_NOT_a_symbol'] # value 2

Labels: , ,

0 Comments:

Post a Comment

Links to this post:

Create a Link

<< Home