diff --git a/features/task_template.feature b/features/task_template.feature new file mode 100644 index 0000000..b2a4725 --- /dev/null +++ b/features/task_template.feature @@ -0,0 +1,27 @@ +Feature: `template' task keyword + + Background: + Given a file named "basic.erb" with: + """ + basic template + """ + Given a file named "variables.erb" with: + """ + <%= @foo %> + """ + + Scenario: renders an ERB template file + Given a recipe with: + """ + task(:echo_template) { echo template 'basic' } + """ + When I execute the recipe + Then the output must contain "basic template" + + Scenario: renders ERB with given attributes as member data + Given a recipe with: + """ + task(:echo_template) { echo template('variables', foo: 'bar') } + """ + When I execute the recipe + Then the output must contain "bar" diff --git a/lib/producer/core.rb b/lib/producer/core.rb index 3bf9a8a..5259b41 100644 --- a/lib/producer/core.rb +++ b/lib/producer/core.rb @@ -1,3 +1,4 @@ +require 'erb' require 'etc' require 'forwardable' require 'optparse' diff --git a/lib/producer/core/task.rb b/lib/producer/core/task.rb index 00a5451..3d3da75 100644 --- a/lib/producer/core/task.rb +++ b/lib/producer/core/task.rb @@ -57,6 +57,25 @@ module Producer def get(key) @env[key] 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 + end end end end