File tree Expand file tree Collapse file tree 3 files changed +27
-6
lines changed
activerecord/lib/active_record/connection_adapters/sqlite3 Expand file tree Collapse file tree 3 files changed +27
-6
lines changed Original file line number Diff line number Diff line change @@ -46,13 +46,20 @@ def type
46
46
def serialize ( value )
47
47
case value
48
48
when ::Numeric , ::Symbol , ActiveSupport ::Duration then value . to_s
49
+ when ::String then serialize_cast_value ( value )
49
50
when true then @true
50
51
when false then @false
51
52
else super
52
53
end
53
54
end
54
55
55
56
def serialize_cast_value ( value ) # :nodoc:
57
+ if value &.encoding == Encoding ::BINARY
58
+ # If we can treat the bytes as UTF-8 without changing them, then use UTF-8 as encoding
59
+ new_value = value . dup . force_encoding ( Encoding ::UTF_8 )
60
+ return new_value if new_value . valid_encoding?
61
+ end
62
+
56
63
value
57
64
end
58
65
Original file line number Diff line number Diff line change @@ -17,6 +17,26 @@ class ImmutableStringTest < ActiveModel::TestCase
17
17
assert_same s , type . cast ( s )
18
18
assert_same s , type . deserialize ( s )
19
19
end
20
+
21
+ test "leaves validly encoded strings untouched" do
22
+ s = "string with àccénts" . encode ( Encoding ::ISO_8859_1 )
23
+ type = Type ::ImmutableString . new
24
+ assert_same s , type . serialize ( s )
25
+ end
26
+
27
+ test "serializes valid, binary-encoded strings to UTF-8" do
28
+ s = "string with àccénts" . b
29
+ type = Type ::ImmutableString . new
30
+ serialized = type . serialize ( s )
31
+ assert_equal Encoding ::UTF_8 , serialized . encoding
32
+ assert_equal s . bytes , serialized . bytes
33
+ end
34
+
35
+ test "leaves true binary data untouched" do
36
+ binary_data = "\xEE \x49 \xC7 " . b
37
+ type = Type ::ImmutableString . new
38
+ assert_same binary_data , type . serialize ( binary_data )
39
+ end
20
40
end
21
41
end
22
42
end
Original file line number Diff line number Diff line change @@ -79,12 +79,6 @@ def type_cast(value) # :nodoc:
79
79
case value
80
80
when BigDecimal
81
81
value . to_f
82
- when String
83
- if value . encoding == Encoding ::ASCII_8BIT
84
- super ( value . encode ( Encoding ::UTF_8 ) )
85
- else
86
- super
87
- end
88
82
else
89
83
super
90
84
end
You can’t perform that action at this time.
0 commit comments