Kouhei Sutou
null+****@clear*****
Thu Jan 2 00:49:40 JST 2014
Kouhei Sutou 2014-01-02 00:49:40 +0900 (Thu, 02 Jan 2014) New Revision: 2251630374234672d5041642c58d0a148e8d5a73 https://github.com/ranguba/chupa-text/commit/2251630374234672d5041642c58d0a148e8d5a73 Message: Support guessing content-type from body Modified files: lib/chupa-text/data.rb test/test-data.rb Modified: lib/chupa-text/data.rb (+16 -1) =================================================================== --- lib/chupa-text/data.rb 2014-01-02 00:38:14 +0900 (ac8c19e) +++ lib/chupa-text/data.rb 2014-01-02 00:49:40 +0900 (6df323e) @@ -99,7 +99,22 @@ module ChupaText end def guess_content_type_from_body - nil + content_type = nil + change_encoding(body, "UTF-8") do |_body| + content_type = "text/plain" if _body.valid_encoding? + end + content_type + end + + def change_encoding(string, encoding) + return if string.nil? + begin + original_encoding = string.encoding + string.force_encoding(encoding) + yield(string) + ensure + string.force_encoding(original_encoding) + end end end end Modified: test/test-data.rb (+20 -6) =================================================================== --- test/test-data.rb 2014-01-02 00:38:14 +0900 (afc878c) +++ test/test-data.rb 2014-01-02 00:49:40 +0900 (20499fd) @@ -28,17 +28,31 @@ class TestData < Test::Unit::TestCase sub_test_case("content-type") do sub_test_case("guess") do - private - def guess(path) - @data.path = path - @data.content_type - end - sub_test_case("extension") do def test_txt ChupaText::ContentType.registry.register("txt", "text/plain") assert_equal("text/plain", guess("README.txt")) end + + private + def guess(path) + @data.path = path + @data.content_type + end + end + + sub_test_case("body") do + def test_txt + body = "Hello" + body.force_encoding("ASCII-8BIT") + assert_equal("text/plain", guess(body)) + end + + private + def guess(body) + @data.body = body + @data.content_type + end end end end -------------- next part -------------- HTML����������������������������...Download