Support YAML templates
This commit is contained in:
parent
82879b56b4
commit
9780cdf220
@ -35,3 +35,15 @@ Feature: `template' task keyword
|
||||
"""
|
||||
When I execute the recipe
|
||||
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$/
|
||||
|
@ -3,6 +3,7 @@ require 'etc'
|
||||
require 'forwardable'
|
||||
require 'optparse'
|
||||
require 'pathname'
|
||||
require 'yaml'
|
||||
|
||||
require 'net/ssh'
|
||||
require 'net/sftp'
|
||||
|
@ -4,21 +4,40 @@ module Producer
|
||||
SEARCH_PATH = 'templates'.freeze
|
||||
|
||||
def initialize(path, search_path: SEARCH_PATH)
|
||||
@path = Pathname.new("#{path}.erb")
|
||||
@path = Pathname.new(path)
|
||||
@search_path = Pathname.new(search_path)
|
||||
end
|
||||
|
||||
def render(variables = {})
|
||||
tpl = ERB.new(File.read(resolve_path), nil, '-')
|
||||
tpl.filename = resolve_path.to_s
|
||||
tpl.result build_erb_binding variables
|
||||
case (file_path = resolve_path).extname
|
||||
when '.yaml' then render_yaml file_path
|
||||
when '.erb' then render_erb file_path, variables
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
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
|
||||
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
|
||||
|
||||
def build_erb_binding(variables)
|
||||
|
1
spec/fixtures/templates/basic_yaml.yaml
vendored
Normal file
1
spec/fixtures/templates/basic_yaml.yaml
vendored
Normal file
@ -0,0 +1 @@
|
||||
foo: bar
|
@ -13,6 +13,14 @@ module Producer::Core
|
||||
expect(template.render).to eq "basic template\n"
|
||||
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
|
||||
let(:path) { 'variables' }
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user