Created
October 28, 2010 01:35
-
-
Save bmuller/650421 to your computer and use it in GitHub Desktop.
ConfigTemplate class
This file contains hidden or 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
| require 'yaml' | |
| require 'erb' | |
| class Struct | |
| def get_binding | |
| binding | |
| end | |
| end | |
| class ConfigTemplate | |
| def initialize(configfile, environment) | |
| conf = YAML.load_file configfile | |
| raise "No such environment: #{environment}" if not conf.has_key? environment | |
| env = conf[environment] | |
| if conf.has_key? 'default' | |
| env = conf['default'].merge env | |
| end | |
| env['environment_name'] = environment | |
| @binding = make_binding env | |
| end | |
| def convert_file(infile, outfile) | |
| e = ERB.new File.open(infile).read | |
| File.open(outfile, 'w') { |f| | |
| f.write e.result(@binding) | |
| } | |
| end | |
| def get(name) | |
| eval name.to_s, @binding | |
| end | |
| def method_missing(name, *args, &block) | |
| get name | |
| end | |
| private | |
| def make_binding(env) | |
| klass = Struct.new *env.keys.map { |k| k.intern } | |
| k = klass.new *env.values | |
| # support up to 5 levels of embedding | |
| 5.times { k = klass.new *env.values.map { |v| ERB.new(v.to_s).result(k.get_binding) } } | |
| k.get_binding | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment