Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby strings with embedded variables

Tags:

ruby

yaml

How can I store ruby string with embedded variables in yaml, but insert variable values only when I get string from yaml?

like image 208
yatagarasu Avatar asked May 31 '12 14:05

yatagarasu


2 Answers

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.
like image 126
steenslag Avatar answered Oct 11 '22 09:10

steenslag


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 ... %>
like image 37
Hooopo Avatar answered Oct 11 '22 08:10

Hooopo