Class: RubyStringTemplate

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

Direct Known Subclasses

Configuration::Path

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
12
13
# File 'lib/httpimagestore/ruby_string_template.rb', line 8

def initialize(template, &resolver)
	super(template.to_s)
	@resolvers = []
	@resolvers << resolver if resolver
	@resolvers << ->(locals, name){locals[name]}
end

Instance Method Details

#add_missing_resolver(&resolver) ⇒ Object

end



53
54
55
# File 'lib/httpimagestore/ruby_string_template.rb', line 53

def add_missing_resolver(&resolver)
	@resolvers << resolver
end

#initialize_copy(source) ⇒ Object



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

def initialize_copy(source)
	super
	# copy resolvers array
	resolvers =
	source.instance_eval do
		resolvers = @resolvers
	end
	@resolvers = resolvers.dup
end

#render(locals = {}) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/httpimagestore/ruby_string_template.rb', line 25

def render(locals = {})
	template = self.to_s
	values = {}

	# use gsub with block instead!
	template.scan(/#\{[^\}]+\}/um).uniq.each do |placeholder|
		name = placeholder.match(/#\{([^\}]*)\}/u).captures.first.to_sym

		value = nil
		@resolvers.find{|resolver| value = resolver.call(locals, name)} or fail NoValueForTemplatePlaceholderError.new(name, self)
		values[placeholder] = value.to_s
	end

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

	template
end

#to_templateObject



45
46
47
# File 'lib/httpimagestore/ruby_string_template.rb', line 45

def to_template
	self
end

#with_missing_resolver(&resolver) ⇒ Object



57
58
59
60
61
# File 'lib/httpimagestore/ruby_string_template.rb', line 57

def with_missing_resolver(&resolver)
	new_template = self.dup
	new_template.add_missing_resolver(&resolver)
	new_template
end