Sha256: 491bd65a5aa536984a6ff929455d6844da701855343e6fe18da6127eb342738c

Contents?: true

Size: 790 Bytes

Versions: 2

Compression:

Stored size: 790 Bytes

Contents

class RubyStringTemplate
	class NoValueForTemplatePlaceholderError < ArgumentError
		def initialize(name, template)
			super "no value for '\#{#{name}}' in template '#{template}'"
		end
	end

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

	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
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
httpimagestore-1.8.0 lib/httpimagestore/ruby_string_template.rb
httpimagestore-1.7.0 lib/httpimagestore/ruby_string_template.rb