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`.



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

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

Class Method Details

.buffer(binding) ⇒ Object

Returns the buffer used for capturing output.



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

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.



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

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(string, *arguments, **options) ⇒ Object



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

def self.load(string, *arguments, **options)
	self.new(Buffer.new(string), **options).freeze
end

.load_file(path, **options) ⇒ Object



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

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

Instance Method Details

#freezeObject



103
104
105
106
107
108
109
# File 'lib/trenni/template.rb', line 103

def freeze
	return self if frozen?
	
	to_proc
	
	super
end

#to_buffer(scope) ⇒ Object



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

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

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



123
124
125
# File 'lib/trenni/template.rb', line 123

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



111
112
113
114
115
116
117
# File 'lib/trenni/template.rb', line 111

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