Created
October 21, 2009 16:55
-
-
Save lukebayes/215270 to your computer and use it in GitHub Desktop.
A Rake Task that makes it stupid-easy to render ERB templates to disk
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 'erb' | |
# DynamicAccessors source file found here: http://gist.github.com/215257 | |
require File.dirname(__FILE__) + '/dynamic_accessors' | |
# Rake task that makes it stupid-easy to render ERB templates | |
# to disk. Just add parameters to the yielded object, and | |
# they will be available to your Template. | |
# | |
# erb_resolver 'config/SomeFile.xml' do |t| | |
# t.param1 = 'value' | |
# t.other_param = 'other value' | |
# t.another_param = ['a', 'b', 'c'] | |
# t.template = 'config/SomeFile.xml.erb' # Optional - will automatically look here... | |
# end | |
# | |
module Sprout | |
class ERBResolver < Rake::FileTask | |
include DynamicAccessors | |
# File to create from the rendered | |
# ERB template. This value will | |
# default to the Task name in order | |
# to be consistent with other FileTasks | |
attr_accessor :output | |
# Path to the input ERB template. This | |
# value will default to the value of | |
# "#{ERBResolver.output}.erb" | |
attr_accessor :template | |
def initialize(name, app) # :nodoc: | |
super | |
end | |
def define | |
end | |
def prepare | |
prepare_prerequisites | |
end | |
def execute(*args) | |
super | |
content = nil | |
File.open(template, 'r') { |f| content = f.read } | |
result = ERB.new(content, nil, '>').result(binding) | |
File.open(output, 'w') { |f| f.write(result) } | |
puts ">> Created ERB output at: #{output} from: #{template}" | |
end | |
def self.define_task(args, &block) | |
t = super | |
if(t.is_a?(ERBResolver)) | |
yield t if block_given? | |
t.define | |
t.prepare | |
end | |
return t | |
end | |
def template | |
@template ||= "#{output}.erb" | |
end | |
def output | |
@output ||= self.name | |
end | |
protected | |
def prepare_prerequisites | |
prerequisites << file(template) | |
CLEAN.add(output) | |
end | |
end | |
end | |
def erb_resolver(args, &block) | |
Sprout::ERBResolver.define_task(args, &block) | |
end |
Thanks for the kind words.
Done.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is a lovely Rake task. Would you be willing to clarify copyright and license for this? I would like to adapt it as part of a code base that will be under the MIT license.