|
| 1 | +#!/usr/bin/env ruby |
| 2 | +require 'erb' |
| 3 | +require 'json' |
| 4 | +require 'yaml' |
| 5 | +require 'optparse' |
| 6 | +require 'ostruct' |
| 7 | + |
| 8 | +class ERBContext |
| 9 | + def initialize(hash) |
| 10 | + raise ArgumentError, 'hash must be a Hash object' unless hash.is_a?(::Hash) |
| 11 | + hash.each do |key, value| |
| 12 | + instance_variable_set :"@#{key}", value |
| 13 | + end |
| 14 | + end |
| 15 | + |
| 16 | + def render(template) |
| 17 | + template.result binding |
| 18 | + end |
| 19 | + |
| 20 | + class << self |
| 21 | + def render(hash, template, safe_level = nil, trim_mode = nil, eoutvar = '_erbout') |
| 22 | + tmpl = ::ERB.new(template, safe_level, trim_mode, eoutvar) |
| 23 | + context = new(hash) |
| 24 | + context.render tmpl |
| 25 | + end |
| 26 | + end |
| 27 | +end |
| 28 | + |
| 29 | +def file_or_stdin(args, stdin = ::STDIN) |
| 30 | + if args.empty? || args.first == '-' |
| 31 | + yield stdin |
| 32 | + else |
| 33 | + File.open args.first, 'r' do |f| |
| 34 | + yield f |
| 35 | + end |
| 36 | + end |
| 37 | +end |
| 38 | + |
| 39 | +def main |
| 40 | + options = OpenStruct.new |
| 41 | + |
| 42 | + parser = OptionParser.new do |opts| |
| 43 | + opts.banner = 'Usage: %s [options] file.erb' % $0 |
| 44 | + opts.on '-y', '--yaml=YAML-FILE', 'YAML file to populate local variables for the template' do |yaml_file| |
| 45 | + File.open yaml_file, 'r' do |f| |
| 46 | + options.yaml = YAML::load(f) |
| 47 | + end |
| 48 | + end |
| 49 | + end |
| 50 | + |
| 51 | + if (args = parser.parse(ARGV)).length > 1 |
| 52 | + STDERR.puts '%s: cannot render more than 1 file at a time!' % $0 |
| 53 | + exit 1 |
| 54 | + end |
| 55 | + |
| 56 | + file_or_stdin args do |input| |
| 57 | + puts ERBContext.render(options.yaml || {}, input.read, nil, '-') |
| 58 | + end |
| 59 | +end |
| 60 | + |
| 61 | +main if __FILE__ == $0 |
0 commit comments