Skip to content

Instantly share code, notes, and snippets.

@troykinsella
Created September 26, 2016 20:50
Show Gist options
  • Save troykinsella/5265d9fa3cd68f521d213844e71faa8c to your computer and use it in GitHub Desktop.
Save troykinsella/5265d9fa3cd68f521d213844e71faa8c to your computer and use it in GitHub Desktop.
A super basic command-line string interpolator in Ruby
#!/usr/bin/env ruby
require 'optparse'
class StringInterpolator
def initialize(inFile, vars)
@in = File.open(inFile).read
@vars = vars
end
def generate
@in.each_line do |line|
@vars.each do |key,val|
line.gsub!("${#{key}}", val || "")
end
puts line
end
end
end
if __FILE__ == $0
file = ''
vars = {}
OptionParser.new do |opts|
opts.banner = "Usage: string-interp.rb [options]"
opts.on('-fFILE', 'The template file to interpolate.') do |v|
file = v
end
opts.on('-vPAIR', 'A variable substitution name=value pair.') do |v|
parts = v.split('=')
vars[parts[0]] = parts[1]
end
end.parse!
StringInterpolator.new(file, vars).generate
end
@troykinsella
Copy link
Author

troykinsella commented Sep 26, 2016

Example usage:

# Input file: vars.yml

---
name: ${name}
cats_owned: ${cats}
crazy: ${crazy}
# Interpolate
$ string-interp.rb \
  -f vars.yml \
  -v name=Ted \
  -v cats=1024 \
  -v crazy=yes \
  > vars_out.yml
# Output file: vars_out.yml

---
name: Ted
cats_owned: 1024
crazy: yes

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment