Class: Lyp::Template
- Inherits:
-
Object
- Object
- Lyp::Template
- Defined in:
- lib/lyp/template.rb
Constant Summary collapse
- EMIT_DELIMITER =
'`'.freeze
- EMIT_RE =
/#{EMIT_DELIMITER}(((?!#{EMIT_DELIMITER}).)*)#{EMIT_DELIMITER}/m
- INTERPOLATION_START =
"{{".freeze
- INTERPOLATION_END =
"}}".freeze
- INTERPOLATION_RE =
/#{INTERPOLATION_START}((?:(?!#{INTERPOLATION_END}).)*)#{INTERPOLATION_END}/m
- ESCAPED_QUOTE =
'\\"'.freeze
- QUOTE =
'"'.freeze
- @@templates =
Global template registry
{}
Class Method Summary collapse
- .load_templates(path) ⇒ Object
- .render(name, arg = {}, env = {}) ⇒ Object
- .set(name, templ) ⇒ Object
Instance Method Summary collapse
- #convert_literal(s) ⇒ Object
-
#initialize(templ) ⇒ Template
constructor
A new instance of Template.
-
#metaclass ⇒ Object
From the metaid gem.
Constructor Details
#initialize(templ) ⇒ Template
Returns a new instance of Template.
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
# File 'lib/lyp/template.rb', line 16 def initialize(templ) templ = templ.gsub(EMIT_RE) {|m| convert_literal($1)} method_str = <<EOF define_method(:render) do |_ = {}, env = {}| __buffer__ = env[:buffer] ||= '' __emit__ = env[:emit] ||= lambda {|s| __buffer__ << s} __render_l__ = env[:render] ||= lambda {|n, o| Template.render(n, o, env)} metaclass.instance_eval "define_method(:__render__) {|n, o| __render_l__[n, o]}" begin #{templ} end __buffer__ end EOF .instance_eval method_str end |
Class Method Details
.load_templates(path) ⇒ Object
46 47 48 |
# File 'lib/lyp/template.rb', line 46 def self.load_templates(path) Dir["#{path}/*.rb"].each {|fn| set(File.basename(fn), IO.read(fn))} end |
.render(name, arg = {}, env = {}) ⇒ Object
54 55 56 57 |
# File 'lib/lyp/template.rb', line 54 def self.render(name, arg = {}, env = {}) raise unless @@templates[name.to_sym] @@templates[name.to_sym].render(arg, env) end |
.set(name, templ) ⇒ Object
50 51 52 |
# File 'lib/lyp/template.rb', line 50 def self.set(name, templ) @@templates[name.to_sym] = new(templ) end |
Instance Method Details
#convert_literal(s) ⇒ Object
34 35 36 37 38 39 40 41 |
# File 'lib/lyp/template.rb', line 34 def convert_literal(s) # look for interpolated values, wrap them with #{} s = s.inspect.gsub(INTERPOLATION_RE) do code = $1.gsub(ESCAPED_QUOTE, QUOTE) "\#{#{code}}" end "__emit__[#{s}]" end |
#metaclass ⇒ Object
From the metaid gem
14 |
# File 'lib/lyp/template.rb', line 14 def ; class << self; self; end; end |