Extract Task#template code in Template class
This commit is contained in:
@@ -41,5 +41,6 @@ require 'producer/core/remote'
|
||||
require 'producer/core/remote/environment'
|
||||
require 'producer/core/remote/fs'
|
||||
require 'producer/core/task'
|
||||
require 'producer/core/template'
|
||||
require 'producer/core/version'
|
||||
require 'producer/core/worker'
|
||||
|
@@ -59,22 +59,7 @@ module Producer
|
||||
end
|
||||
|
||||
def template(path, variables = {})
|
||||
path = "#{path}.erb"
|
||||
tpl = ERB.new(File.read(path), nil, '-')
|
||||
tpl.filename = path
|
||||
tpl.result build_erb_binding variables
|
||||
end
|
||||
|
||||
|
||||
private
|
||||
|
||||
def build_erb_binding(variables)
|
||||
Object.new.instance_eval do |o|
|
||||
variables.each do |k, v|
|
||||
o.instance_variable_set "@#{k}", v
|
||||
end
|
||||
binding
|
||||
end
|
||||
Template.new(path).render variables
|
||||
end
|
||||
end
|
||||
end
|
||||
|
34
lib/producer/core/template.rb
Normal file
34
lib/producer/core/template.rb
Normal file
@@ -0,0 +1,34 @@
|
||||
module Producer
|
||||
module Core
|
||||
class Template
|
||||
SEARCH_PATH = 'templates'.freeze
|
||||
|
||||
def initialize(path, search_path: SEARCH_PATH)
|
||||
@path = Pathname.new("#{path}.erb")
|
||||
@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
|
||||
end
|
||||
|
||||
|
||||
private
|
||||
|
||||
def resolve_path
|
||||
if @path.to_s =~ /\A\.\// then @path else @search_path + @path end
|
||||
end
|
||||
|
||||
def build_erb_binding(variables)
|
||||
Object.new.instance_eval do |o|
|
||||
variables.each do |k, v|
|
||||
o.instance_variable_set "@#{k}", v
|
||||
end
|
||||
binding
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
Reference in New Issue
Block a user