How can I store ruby string with embedded variables in yaml, but insert variable values only when I get string from yaml?
Asked
Active
Viewed 5,603 times
9
-
what do you mean by string with embedded variables? Are you sure you want to insert variable *names* only ... – Ivaylo Strandjev May 31 '12 at 14:04
-
He wants to do interpolation later. I guess. – Sergio Tulentsev May 31 '12 at 14:05
-
I read the question as wanting to do something like "Text for Yaml #{variable}".to_yaml where the variable is not evaluated before it is sent to yaml. – vlasits May 31 '12 at 14:12
-
**See also:** https://stackoverflow.com/questions/41620674/use-placeholders-in-yaml – dreftymac Dec 30 '19 at 22:40
2 Answers
19
str = "Hi %{name}, %{msg}. Bye %{name}." #yaml it, de-yaml it back to string
h = {:name=> "John", :msg=> "this message is for you"}
puts str % h
#=>Hi John, This message is for you. Bye John.

steenslag
- 79,051
- 16
- 138
- 171
2
Embed erb in yaml file as rails did:
# config/initializers/load_config.rb
APP_CONFIG = YAML.load_file("#{Rails.root}/config/app_config.yml")[Rails.env]
# config/app_config.yml
development:
key1: <%= # ruby code ... %>
test:
key1: <%= # ruby code ... %>
production:
key1: <%= # ruby code ... %>

Hooopo
- 1,380
- 10
- 16