Rails load YAML to hash and reference by symbol

前端 未结 11 2174
慢半拍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

    An alternative solution is to have the keys which you wish to access as a symbol prepended with a colon. For example:

    default: &default
      :symbol: "Accessed via a symbol only"
      string: "Accessed via a string only"
    
    development:
      <<: *default
    
    test:
      <<: *default
    
    production:
      <<: *default
    

    Later you can then access these like so:

    APP_CONFIG[:symbol]
    APP_CONFIG['string']
    

    Note that I am using YAML::ENGINE.yamler = "syck". Not sure if this works with psych. (Psych definitely won't support key merging as I showed in the example though.)

    About using HashWithIndifferentAccess: using it has the side effect of creating duplicate keys: one for symbol access and one for string access. This might be nefarious if you pass around YAML data as arrays. Be aware of this if you go with that solution.

提交回复
热议问题