Rails load YAML to hash and reference by symbol

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

    If you're using pure Ruby (i.e. no Rails), you could intermediately change to JSON format. The JSON lib's parse method can symbolize keys.

    http://ruby-doc.org/stdlib-2.0.0/libdoc/json/rdoc/JSON.html#method-i-parse

    Here's what I mean:

    JSON.parse(JSON.dump(YAML.load_file(File.expand_path('../app.yml', __FILE__))), symbolize_names: true)
    

    Note: This adds overhead of conversion to and from json.

提交回复
热议问题