Michael Granger avatar Michael Granger committed 2202c6e

Transcode output according to the :encoding option if set on a template

Comments (0)

Files changed (3)

lib/inversion/renderstate.rb

 		if self.rendering_enabled?
 			self.destination << self.make_node_comment( node ) if self.options[:debugging_comments]
 			previous_node = nil
+			enc = self.options[:encoding] || Encoding.default_internal
 
 			begin
 				# Allow render to be delegated to subobjects
 					node = node.render( self )
 				end
 
-				# self.log.debug "  adding a %p to the destination (%p)" %
-				# 	[ node.class, self.destination.class ]
+				# self.log.debug "  adding a %p (%p; encoding: %s) to the destination (%p)" %
+				#	[ node.class, node, node.respond_to?(:encoding) ? node.encoding : 'n/a', self.destination.class ]
 				self.destination << node
 				# self.log.debug "    just appended %p to %p" % [ node, self.destination ]
 			rescue ::StandardError => err
 
 	### Turn the rendered node structure into the final rendered String.
 	def to_s
-		return @output.flatten.map( &:to_s ).join
+		strings = @output.flatten.map( &:to_s )
+
+		if enc = self.options[ :encoding ]
+			self.log.debug "Encoding rendered template parts to %s" % [ enc ]
+			strings.map! {|str| str.encode(enc) }
+		end
+
+		return strings.join
 	end
 
 

lib/inversion/template.rb

 		end
 
 		# We trust files read from disk
-		encoding = opts.delete( :encoding )
-		source = if encoding
-				tmpl.read( encoding: encoding )
+		source = if opts.key?( :encoding )
+				tmpl.read( encoding: opts[:encoding] )
 			else
 				tmpl.read
 			end

spec/inversion/renderstate_spec.rb

 #!/usr/bin/env rspec -cfd -b
+# encoding: utf-8
 # vim: set noet nosta sw=4 ts=4 :
 
 BEGIN {
 
 	end
 
+
+	describe "encoding support" do
+
+		it "transcodes attribute values if the template's encoding is set" do
+			attributes = {
+				good_doggie: "Стрелка".encode('koi8-u'),
+				little:      "arrow".encode('us-ascii')
+			}
+
+			state = Inversion::RenderState.new( attributes, encoding: 'utf-8' )
+
+			state << Inversion::Template::AttrTag.new( 'good_doggie' )
+			state << Inversion::Template::AttrTag.new( 'little' )
+
+			state.to_s.encoding.should be( Encoding::UTF_8 )
+		end
+
+	end
+
 end
 
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.