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
25
26
27
28
29
# File 'lib/httpimagestore/ruby_string_template.rb', line 13

def render(locals = {})
	template = @template.dup
	values = {}

	template.scan(/#\{[^\}]+\}/um).uniq.each do |placeholder|
		name = placeholder.match(/#\{([^\}]*)\}/u).captures.first.to_sym
		value = @resolver.call(locals, name)
		value or fail NoValueForTemplatePlaceholderError.new(name, @template)
		values[placeholder] = value.to_s
	end

	values.each_pair do |placeholder, value|
		template.gsub!(placeholder, value)
	end

	template
end