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



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

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

Class Method Details

.buffer(binding) ⇒ Object

Returns the buffer used for capturing output.



63
64
65
# File 'lib/trenni/template.rb', line 63

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

.capture(*args, &block) ⇒ Object

Returns the output produced by calling the given block.



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/trenni/template.rb', line 46

def self.capture(*args, &block)
	scope = block.binding
	output_buffer = scope.local_variable_get(OUT)
	
	capture_buffer = String.new.force_encoding(output_buffer.encoding)
	scope.local_variable_set(OUT, capture_buffer)
	
	begin
		block.call(*args)
	ensure
		scope.local_variable_set(OUT, output_buffer)
	end
	
	return capture_buffer
end

.load_file(path, *args) ⇒ Object



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

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

Instance Method Details

#freezeObject



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

def freeze
	return self if frozen?
	
	to_proc
	
	super
end

#to_buffer(scope) ⇒ Object



121
122
123
# File 'lib/trenni/template.rb', line 121

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

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



125
126
127
# File 'lib/trenni/template.rb', line 125

def to_proc(scope = @binding.dup)
	@compiled_proc ||= eval("proc{|#{OUT}|;#{code}}", scope, @buffer.path).freeze
end

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



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

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