Permalink
Browse files

Set encoding for inline templates correctly.

* If Ruby version is not encoding aware, do nothing
* If file contains a magic comment in the first line, use that encoding
* Otherwise use settings.default_encoding

Allows one to use unicode characters without having to escape them and deploy
on Linux systems, like Heroku, on 1.9.2 (on OSX encodings always default to
UTF-8, which makes it hard to spot this issue before deployment).

Fixes #136.
  • Loading branch information...
1 parent f29054a commit 5b941ab2a2fa2dd219cc9b0f8ff148ba41c7c3c4 @rkh rkh committed Dec 13, 2010
Showing with 26 additions and 9 deletions.
  1. +16 −9 lib/sinatra/base.rb
  2. +10 −0 test/templates_test.rb
View
@@ -917,15 +917,20 @@ def inline_templates=(file=nil)
end
if data
+ if app and app.lines.first =~ /^\s*#\W*encoding\W*(\w[\w_\-\.\d]+)\W*$/
+ encoding = $1
+ else
+ encoding = settings.default_encoding
+ end
lines = app.count("\n") + 1
template = nil
data.each_line do |line|
lines += 1
if line =~ /^@@\s*(.*\S)\s*$/
- template = ''
+ template = force_encoding('', encoding)
templates[$1.to_sym] = [template, file, lines]
elsif template
- template << line
+ template << force_encoding(line, encoding)
end
end
end
@@ -1227,20 +1232,22 @@ def caller_locations
#
# The latter might not be necessary if Rack handles it one day.
# Keep an eye on Rack's LH #100.
+ def force_encoding(*args) settings.force_encoding(*args) end
if defined? Encoding
- def force_encoding(data)
- return if data == self || data.is_a?(Tempfile)
+ def self.force_encoding(data, encoding = default_encoding)
+ return if data == settings || data.is_a?(Tempfile)
if data.respond_to? :force_encoding
- data.force_encoding settings.default_encoding
+ data.force_encoding encoding
elsif data.respond_to? :each_value
- data.each_value { |v| force_encoding(v) }
+ data.each_value { |v| force_encoding(v, encoding) }
elsif data.respond_to? :each
- data.each { |v| force_encoding(v) }
+ data.each { |v| force_encoding(v, encoding) }
end
+ data
end
else
- def force_encoding(*) end
- end
+ def self.force_encoding(data, *) data end
+ end
reset!
@@ -1,3 +1,4 @@
+# encoding: UTF-8
require File.dirname(__FILE__) + '/helper'
File.delete(File.dirname(__FILE__) + '/views/layout.test') rescue nil
@@ -137,6 +138,12 @@ def with_default_layout
assert @app.templates.empty?
end
+ it 'allows unicode in inline templates' do
+ mock_app { set :inline_templates, __FILE__ }
+ assert_equal "Den som tror at hemma det är där man bor har aldrig vart hos mig.\n\n",
+ @app.templates[:umlaut][0]
+ end
+
it 'loads templates from specified views directory' do
render_app { render :test, :hello, :views => options.views + '/foo' }
@@ -216,6 +223,9 @@ def with_default_layout
@@ foo bar
this is not foo
+@@ umlaut
+Den som tror at hemma det är där man bor har aldrig vart hos mig.
+
@@ layout
X
= yield

0 comments on commit 5b941ab

Please sign in to comment.