Support YAML templates

This commit is contained in:
Thibault Jouan 2014-10-10 18:56:26 +00:00
parent 82879b56b4
commit 9780cdf220
5 changed files with 46 additions and 5 deletions

View File

@ -35,3 +35,15 @@ Feature: `template' task keyword
""" """
When I execute the recipe When I execute the recipe
Then the output must contain "basic template" Then the output must contain "basic template"
Scenario: parses a yaml file
Given a file named "templates/basic.yaml" with:
"""
foo: bar
"""
And a recipe with:
"""
task(:echo_template) { echo template('basic')['foo'] }
"""
When I execute the recipe
Then the output must match /^bar$/

View File

@ -3,6 +3,7 @@ require 'etc'
require 'forwardable' require 'forwardable'
require 'optparse' require 'optparse'
require 'pathname' require 'pathname'
require 'yaml'
require 'net/ssh' require 'net/ssh'
require 'net/sftp' require 'net/sftp'

View File

@ -4,21 +4,40 @@ module Producer
SEARCH_PATH = 'templates'.freeze SEARCH_PATH = 'templates'.freeze
def initialize(path, search_path: SEARCH_PATH) def initialize(path, search_path: SEARCH_PATH)
@path = Pathname.new("#{path}.erb") @path = Pathname.new(path)
@search_path = Pathname.new(search_path) @search_path = Pathname.new(search_path)
end end
def render(variables = {}) def render(variables = {})
tpl = ERB.new(File.read(resolve_path), nil, '-') case (file_path = resolve_path).extname
tpl.filename = resolve_path.to_s when '.yaml' then render_yaml file_path
tpl.result build_erb_binding variables when '.erb' then render_erb file_path, variables
end
end end
private private
def render_erb(file_path, variables = {})
tpl = ERB.new(File.read(file_path), nil, '-')
tpl.filename = file_path.to_s
tpl.result build_erb_binding variables
end
def render_yaml(file_path)
YAML.load(File.read(file_path))
end
def resolve_path def resolve_path
if @path.to_s =~ /\A\.\// then @path else @search_path + @path end if @path.to_s =~ /\A\.\//
resolve_suffix @path
else
resolve_suffix @search_path + @path
end
end
def resolve_suffix(path)
Pathname.glob("#{path}.{erb,yaml}").first
end end
def build_erb_binding(variables) def build_erb_binding(variables)

View File

@ -0,0 +1 @@
foo: bar

View File

@ -13,6 +13,14 @@ module Producer::Core
expect(template.render).to eq "basic template\n" expect(template.render).to eq "basic template\n"
end end
context 'yaml templates' do
let(:path) { 'basic_yaml' }
it 'renders yaml templates' do
expect(template.render).to eq({ 'foo' => 'bar' })
end
end
context 'when variables are given' do context 'when variables are given' do
let(:path) { 'variables' } let(:path) { 'variables' }