Preethi Kumar
Preethi Kumar

Reputation: 1531

How to make my YAML produces actual value of my Ruby code

I have a yaml file,

---
 - time1: <%= Date.today %>
   value: "string"
  

After I load my YAML, the Ruby code is printed as string. How I get the actual Date.today value?

{"time1"=>"<%= Date.today %>"}

Upvotes: 0

Views: 36

Answers (1)

mechnicov
mechnicov

Reputation: 15298

yaml =
  <<~YAML
    ---
      - time1: <%= Date.today %>
        value: "string"
  YAML

Firstly you need to apply ERB to your string using result to execute Ruby code

And only after that parse it with YAML

YAML.load(ERB.new(yaml).result)
# => [{"time1"=>Thu, 08 Sep 2022, "value"=>"string"}]

Probably you skipped first step to execute embedded Ruby and interpolate into original string

ERB.new(yaml).result
# => "---\n  - time1: 2022-09-08\n    value: \"string\"\n"

Of course you need

require 'erb'
require 'yaml'

if don't use Rails

Upvotes: 1

Related Questions