Rails load YAML to hash and reference by symbol

前端 未结 11 2057
慢半拍i
慢半拍i 2021-02-01 12:22

I am loading a YAML file in Rails 3.0.9 like this:

APP_CONFIG = YAML.load(File.read(File.expand_path(\'../app.yml\', __FILE__)))

It loads the a

11条回答
  •  南方客
    南方客 (楼主)
    2021-02-01 12:35

    You are probably used to the params hash in Rails, which is actually a HashWithIndifferentAccess rather than a standard ruby Hash object. This allows you to use either strings like 'action' or symbols like :action to access the contents.

    With a HashWithIndifferentAccess, you will get the same results regardless of what you use, but keep in mind this only works on HashWithIndifferentAccess objects.

    So to make this work with YAML, you'll have to load the result of YAML.load into a HashWithIndifferentAccess, like so:

    APP_CONFIG = HashWithIndifferentAccess.new(   YAML.load(File.read(File.expand_path('../app.yml', __FILE__)))   )
    

提交回复
热议问题