Skip to content

Commit 70878b6

Browse files
committed
use force_encoding instread of encode! to avoid UndefinedConversionError
`PG::TextEncoder::Array#encode` returns the encoded value with `ASCII-8BIT`. But in some cases, trying to convert `ASCII-8BIT` to `UTF-8` cause an error. ```ruby "{\xE3\x83\x95\xE3\x82\xA1\xE3\x82\xA4\xE3\x83\xAB}".encode!(Encoding::UTF_8) # => Encoding::UndefinedConversionError: "\xE3" from ASCII-8BIT to UTF-8 ``` Should use `force_encoding` to avoid this error. Follow up to 7ba3a48 Ref: rails#23619 (comment)
1 parent cfa5cab commit 70878b6

File tree

2 files changed

+4
-4
lines changed
  • activerecord

2 files changed

+4
-4
lines changed

activerecord/lib/active_record/connection_adapters/postgresql/oid/array.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ def serialize(value)
3535
if value.is_a?(::Array)
3636
result = @pg_encoder.encode(type_cast_array(value, :serialize))
3737
if encoding = determine_encoding_of_strings(value)
38-
result.encode!(encoding)
38+
result.force_encoding(encoding)
3939
end
4040
result
4141
else

activerecord/test/cases/adapters/postgresql/array_test.rb

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -312,9 +312,9 @@ def self.model_name; ActiveModel::Name.new(PgArray) end
312312
end
313313

314314
def test_encoding_arrays_of_utf8_strings
315-
string_with_utf8 = "nový"
316-
assert_equal [string_with_utf8], @type.deserialize(@type.serialize([string_with_utf8]))
317-
assert_equal [[string_with_utf8]], @type.deserialize(@type.serialize([[string_with_utf8]]))
315+
arrays_of_utf8_strings = %w(nový ファイル)
316+
assert_equal arrays_of_utf8_strings, @type.deserialize(@type.serialize(arrays_of_utf8_strings))
317+
assert_equal [arrays_of_utf8_strings], @type.deserialize(@type.serialize([arrays_of_utf8_strings]))
318318
end
319319

320320
private

0 commit comments

Comments
 (0)