How do I use variables in a YAML file?

2019-02-12 18:45发布

问题:

I have YAML file which needs to take a variable as an input:

outputters:
    - type        : DateFileOutputter
      name        : logfile
      level       : DEBUG
      date_pattern: '%Y%m%d'
      trunc       : 'false'
      dirname     : "/home/sameera/workspace/project/log"
      filename    : "message.log"
      formatter   :
        date_pattern: '%m/%d/%Y %H:%M:%S'
        pattern     : '%d %l - %m'
        type        : PatternFormatter

I want to pass dirname as a parameter, something like:

      dirname     : "<%= LOGFILE_PATH%>"

My LOGFILE_PATH is defined in a file called init.rb.

回答1:

You could use ERB.

For example:

template = ERB.new File.new("path/to/config.yml.erb").read
processed = YAML.load template.result(binding)

You can read more on binding here: ruby metaprogramming.