diff --git a/lib/sinatra/base.rb b/lib/sinatra/base.rb index 76b47c63..3f5abd0d 100644 --- a/lib/sinatra/base.rb +++ b/lib/sinatra/base.rb @@ -428,6 +428,7 @@ module Sinatra @response = Response.new @params = indifferent_params(@request.params) template_cache.clear if settings.reload_templates + force_encoding(@params) invoke { dispatch! } invoke { error_block!(response.status) } @@ -1093,6 +1094,31 @@ module Sinatra end end + attr_reader :default_encoding + def default_encoding=(value) + return false unless defined? Encoding + case value + when :utf8, true + self.default_encoding = "UTF-8" + when false + @default_encoding = value + else + Encoding.default_external = value + @default_encoding = Encoding.default_external + end + end + + def force_encoding(data, encoding = default_encoding) + return if !encoding or data == self + if data.respond_to? :force_encoding + data.force_encoding(encoding) + elsif data.respond_to? :each_value + data.each_value { |v| force_encoding(v, encoding) } + elsif data.respond_to? :each + data.each { |v| force_encoding(v, encoding) } + end + end + reset! set :environment, (ENV['RACK_ENV'] || :development).to_sym @@ -1118,6 +1144,7 @@ module Sinatra set :root, Proc.new { app_file && File.expand_path(File.dirname(app_file)) } set :views, Proc.new { root && File.join(root, 'views') } set :reload_templates, Proc.new { development? or RUBY_VERSION < '1.8.7' } + set :default_encoding, 'UTF-8' set :lock, false set :public, Proc.new { root && File.join(root, 'public') } diff --git a/test/settings_test.rb b/test/settings_test.rb index 821376c2..4b640ff3 100644 --- a/test/settings_test.rb +++ b/test/settings_test.rb @@ -1,3 +1,4 @@ +# encoding: UTF-8 require File.dirname(__FILE__) + '/helper' class SettingsTest < Test::Unit::TestCase @@ -374,4 +375,11 @@ class SettingsTest < Test::Unit::TestCase assert ! @application.lock? end end + + describe 'default_encoding' do + it 'allows unicode strings in ascii templates per default (1.9)' do + @base.set :views, File.dirname(__FILE__) + "/views" + @base.new.haml(:ascii, {}, :value => "åkej") + end + end end diff --git a/test/views/ascii.haml b/test/views/ascii.haml new file mode 100644 index 00000000..f410b319 --- /dev/null +++ b/test/views/ascii.haml @@ -0,0 +1,2 @@ +This file has no unicode in it! += value