string variable interpolation from file in ruby

posted by alexis reigel on december 17, 2012

Sometimes you want to interpolate your variables from a dynamic string, e.g. some settings from a yaml file. The top three options are:

  • use eval() to interpolate the variables in the form of #{foo}
  • use some templating engine like erb or mustache or whatever
  • use the string format operator

I’ll show the third option here as:

  • eval() is dangerous for externally read sources and the yaml needs to be aware of the variables and scopes where the string is interpolated in the source code
  • a templating engine is overkill for this purpose

Ruby has string formatting support and a very handy % operator. This enables us to replace certain parts of our config at runtime with the actual value, like this:

"foo = %{foo}" % { :foo => 'bar' }

Metaflop serves once again as a sample application. The following shows the perl command to generate some parts of our fonts (simplified):
config.yml:

font_otf: perl mf2pt1.pl --family=%{fontface} --nofixedpitch --fullname="%{fontface} %{font_hash}" font.mf

Assuming we have a “config” variable that holds all the values defined in yaml we can do:

config.font_otf % {
  :fontface => 'Bespoke',
  :font_hash => '234sdof23nsf'}

# => perl mf2pt1.pl --family=Bespoke --nofixedpitch --fullname="Bespoke 234sdof23nsf" font.mf

The operator accepts literals and arrays as arguments as well, but I like the named parameters style best. This way, there is an obvious connection between the placeholder and its value.