Class: Trenni::Template

Inherits:
Object
  • Object
show all
Defined in:
lib/trenni/template.rb

Direct Known Subclasses

MarkupTemplate

Defined Under Namespace

Classes: Assembler

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(buffer, binding: BINDING) ⇒ Template

Returns a new instance of Template.

Parameters:

  • binding (Binding) (defaults to: BINDING)

    The binding in which the template is compiled. e.g. ‘TOPLEVEL_BINDING`.



93
94
95
96
# File 'lib/trenni/template.rb', line 93

def initialize(buffer, binding: BINDING)
	@buffer = buffer
	@binding = binding
end

Class Method Details

.buffer(binding) ⇒ Object

Returns the buffer used for capturing output.



56
57
58
# File 'lib/trenni/template.rb', line 56

def self.buffer(binding)
	binding.local_variable_get(OUT)
end

.capture(*arguments, output: nil, &block) ⇒ Object

Returns the output produced by calling the given block.



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/trenni/template.rb', line 39

def self.capture(*arguments, output: nil, &block)
	scope = block.binding
	previous_output = scope.local_variable_get(OUT)
	
	output ||= previous_output.class.new(encoding: previous_output.encoding)
	scope.local_variable_set(OUT, output)
	
	begin
		block.call(*arguments)
	ensure
		scope.local_variable_set(OUT, previous_output)
	end
	
	return output
end

.load_file(path, *args) ⇒ Object



88
89
90
# File 'lib/trenni/template.rb', line 88

def self.load_file(path, *args)
	self.new(FileBuffer.new(path), *args).freeze
end

Instance Method Details

#freezeObject



98
99
100
101
102
103
104
# File 'lib/trenni/template.rb', line 98

def freeze
	return self if frozen?
	
	to_proc
	
	super
end

#to_buffer(scope) ⇒ Object



114
115
116
# File 'lib/trenni/template.rb', line 114

def to_buffer(scope)
	Buffer.new(to_string(scope), path: @buffer.path)
end

#to_proc(scope = @binding.dup) ⇒ Object



118
119
120
# File 'lib/trenni/template.rb', line 118

def to_proc(scope = @binding.dup)
	@compiled_proc ||= eval("\# frozen_string_literal: true\nproc{|#{OUT}|;#{code}}", scope, @buffer.path, 0).freeze
end

#to_string(scope = Object.new, output = nil) ⇒ Object



106
107
108
109
110
111
112
# File 'lib/trenni/template.rb', line 106

def to_string(scope = Object.new, output = nil)
	output ||= output_buffer
	
	scope.instance_exec(output, &to_proc)
	
	return output
end