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 WorldYou can get the indifferenct access behavior in YAML files by putting this at the top of your YAML file:
--- !map:HashWithIndifferentAccessThat 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 2Once 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
1 comments:
Thanks for this post Nick! You saved me a lot of time.
Post a Comment