Class: Inprovise::Template
- Inherits:
-
Object
- Object
- Inprovise::Template
- Defined in:
- lib/inprovise/template.rb
Instance Method Summary collapse
-
#initialize(path, context = nil) ⇒ Template
constructor
A new instance of Template.
- #render(locals = {}) ⇒ Object
- #render_to(fname, *opts, &block) ⇒ Object
- #render_to_tempfile(locals = {}) ⇒ Object
Constructor Details
#initialize(path, context = nil) ⇒ Template
Returns a new instance of Template.
11 12 13 14 15 |
# File 'lib/inprovise/template.rb', line 11 def initialize(path, context = nil) @context = context || Object.new @path = resolve(path) @template = @path.respond_to?(:call) ? Tilt['erb'].new(&@path) : Tilt.new(@path) end |
Instance Method Details
#render(locals = {}) ⇒ Object
17 18 19 |
# File 'lib/inprovise/template.rb', line 17 def render(locals={}) @template.render(Inprovise::ExecutionContext::DSL.new(@context), locals) end |
#render_to(fname, *opts, &block) ⇒ Object
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
# File 'lib/inprovise/template.rb', line 21 def render_to(fname, *opts, &block) locals = Hash === opts.last ? opts.pop : {} mktmp = (opts.size) > 0 ? opts.shift : true tmpfile = @context.local(render_to_tempfile(locals)) fremote = nil begin # upload to temporary file fremote = tmpfile.upload("#{File.basename(fname, '.*')}-#{tmpfile.hash}#{File.extname(fname)}") # move/rename temporary file if required unless mktmp && File.dirname(fname) == '.' fremote = fremote.move_to(mktmp ? File.dirname(fname) : fname) end if block_given? @context.exec(block, fremote) fremote.delete! if mktmp fremote = nil end ensure tmpfile.delete! end fremote end |
#render_to_tempfile(locals = {}) ⇒ Object
44 45 46 47 48 49 50 |
# File 'lib/inprovise/template.rb', line 44 def render_to_tempfile(locals={}) basename = @path.respond_to?(:call) ? 'inprovise-inline-tpl' : File.basename(@path).tr('.', '-') file = Tempfile.new(basename) file.write render(locals) file.close file.path end |