Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Better handling of encodings in Ruby 1.9, defaults to UTF-8. Fixes GH #…

…27, GH #38 and params issue that came up in IRC.
  • Loading branch information...
commit 7289cd905c6b36b5c669fbbce1cc2bb00ddb0a39 1 parent 0dd5749
Konstantin Haase authored
27 lib/sinatra/base.rb
View
@@ -428,6 +428,7 @@ def call!(env)
@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 @@ def caller_locations
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 @@ class << self
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') }
8 test/settings_test.rb
View
@@ -1,3 +1,4 @@
+# encoding: UTF-8
require File.dirname(__FILE__) + '/helper'
class SettingsTest < Test::Unit::TestCase
@@ -374,4 +375,11 @@ def foo=(value)
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
2  test/views/ascii.haml
View
@@ -0,0 +1,2 @@
+This file has no unicode in it!
+= value
Please sign in to comment.
Something went wrong with that request. Please try again.