Rails load YAML to hash and reference by symbol

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

    Just use appropriate option in your YAML parser. For instance, symbolize_names in Psych:

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

    See RDoc: https://ruby-doc.org/stdlib-2.6.1/libdoc/psych/rdoc/Psych.html#method-c-load.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-01 12:43

    Psych (a.k.a. YAML) provides the keyword argument :symbolize_names to load keys as symbols. See method reference

    file_path = File.expand_path('../app.yml', __FILE__)
    yaml_contents = File.read(file_path)
    
    APP_CONFIG = YAML.safe_load(yaml_contents, symbolize_names: true)
    
    0 讨论(0)
  • 2021-02-01 12:44

    This is the same from the selected answer, but with a better syntax:

    YAML.load(File.read(file_path)).with_indifferent_access 
    
    0 讨论(0)
  • 2021-02-01 12:50

    I usually don't use HashWithIndifferentAccess just to avoid confusion and prevent inconsistencies in the way that it is accessed, so what I would do instead is tack on a .deep_symbolize_keys to get the whole thing in symbol key form.

    0 讨论(0)
提交回复
热议问题