2

I'm trying to improve my YAML file for my Vagrant project. According to this post, if I have something like this:

en:
  site_name: "Site Name"
  static_pages:
    company:
      description: ! '%{site_name} is an online system'

I should be able to print "Site Name is an online system", but I don't know how to use it inside my Vagrantfile. I tried so far but I couldn't print it out properly, just this:

%{site_name} is an online system

This is how I'm using it:

require 'yaml'
set = YAML.load_file(ENV['DEVOPS_HOME'] + '/vagrant/server/settings.yml')
puts set['en']['static_pages']['company']['description']
Community
  • 1
  • 1
Valter Silva
  • 16,446
  • 52
  • 137
  • 218

2 Answers2

3

as they say in the answer of the post

and then call in the appropriate view with the site name as a parameter

so you don't get directly after you load the yaml file the expected string, you need to match the parameter. one way you could work this in your Vagrantfile is

require 'yaml'
set = YAML.load_file(ENV['DEVOPS_HOME'] + '/vagrant/server/settings.yml')
str = set['en']['static_pages']['company']['description']
arg = {:site_name=> set['en']['site_name']}
p str % arg

will print out "Site Name is an online system"

The other way would be to use the answer from mudasobwa which is also detailed in the original post you reference

Frederic Henri
  • 51,761
  • 10
  • 113
  • 139
  • You have helped me once again @Frédéric! Thank you mate! :) – Valter Silva Jun 22 '16 at 09:40
  • welcome Valter - depending your use case, the other is more simple but if you have variable in the middle of the string, join will not work and the resolution of parameter would be needed, for example if you had the string _'welcome on %{site_name} - we are online !'_ a simple join will not make the parameter at specific location, also if you have multiple variables it might be better to work with parameter than join – Frederic Henri Jun 22 '16 at 13:39
2

You might want to use YAML aliases to achieve this functionality:

en:
  site_name: &site_name "Site Name" # declaring alias
  static_pages:
    company:
      description: 
        - *site_name                # reference
        - "is an online system"

And later on:

puts set['en']['static_pages']['company']['description'].join(' ')
Aleksei Matiushkin
  • 119,336
  • 10
  • 100
  • 160
  • 1
    I have read about `aliases` but I didn't get it. But with your example I could understand it. Thank you @mudasobwa! – Valter Silva Jun 22 '16 at 09:41