/
erb_handler.rb
60 lines (54 loc) · 1.7 KB
/
erb_handler.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
module Padrino
module Helpers
module OutputHelpers
##
# Handler for reading and writing from an erb template.
#
class ErbHandler < AbstractHandler
attr_reader :output_buffer
def initialize(template)
super
@output_buffer = template.instance_variable_get(:@_out_buf)
end
##
# Captures the html from a block of template code for this handler.
#
# @example
# @handler.capture_from_template(&block) => "...html..."
#
def capture_from_template(*args, &block)
self.output_buffer, _buf_was = ActiveSupport::SafeBuffer.new, self.output_buffer
raw = block.call(*args)
captured = template.instance_variable_get(:@_out_buf)
self.output_buffer = _buf_was
engine_matches?(block) ? captured : raw
end
##
# Outputs the given text to the templates buffer directly.
#
# @example
# @handler.concat_to_template("This will be output to the template buffer")
#
def concat_to_template(text="")
self.output_buffer << text if text
nil
end
##
# Returns true if the block given is of the handler's template type; false otherwise.
#
# @example
# @handler.engine_matches?(block) => true
#
def engine_matches?(block)
block.binding.eval('defined? __in_erb_template')
end
protected
def output_buffer=(val)
template.instance_variable_set(:@_out_buf, val)
end
end
OutputHelpers.register(:erb, ErbHandler)
OutputHelpers.register(:erubis, ErbHandler)
end
end
end