Created
September 26, 2016 20:50
-
-
Save troykinsella/5265d9fa3cd68f521d213844e71faa8c to your computer and use it in GitHub Desktop.
A super basic command-line string interpolator in Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example usage: