Class: RubyStringTemplate

Inherits:
Object
  • Object
show all
Defined in:
lib/httpimagestore/ruby_string_template.rb

Defined Under Namespace

Classes: NoValueForTemplatePlaceholderError

Instance Method Summary collapse

Constructor Details

#initialize(template, &resolver) ⇒ RubyStringTemplate

Returns a new instance of RubyStringTemplate.



8
9
10
11
# File 'lib/httpimagestore/ruby_string_template.rb', line 8

def initialize(template, &resolver)
	@template = template.to_s
	@resolver = resolver ? resolver : ->(locals, name){locals[name]}
end

Instance Method Details

#render(locals = {}) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/httpimagestore/ruby_string_template.rb', line 13

def render(locals = {})
	template = @template
	while tag = template.match(/(#\{[^\}]+\})/m)
		tag = tag.captures.first
		name = tag.match(/#\{([^\}]*)\}/).captures.first.to_sym
		value = @resolver.call(locals, name)
		value or fail NoValueForTemplatePlaceholderError.new(name, @template)
		value = value.to_s
		template = template.gsub(tag, value)
	end
	template
end