From 38151711c8a3ee6ebecfce223ad92d7e2f4468ef Mon Sep 17 00:00:00 2001 From: r-plus Date: Sat, 13 Jan 2024 22:06:28 +0900 Subject: [PATCH] Fix IPAddr prefix information missing when write to cache in msgpack serializer * Save cache size by omit the prefix if unnecessary * rename to straightforward naming. * check the prefix directly instead of inspect * Remove unused helper method * add to changelog Co-authored-by: Jonathan Hefner --- activesupport/CHANGELOG.md | 7 +++++++ .../active_support/message_pack/extensions.rb | 17 +++++++++++++++-- .../message_pack/shared_serializer_tests.rb | 6 ++++++ 3 files changed, 28 insertions(+), 2 deletions(-) diff --git a/activesupport/CHANGELOG.md b/activesupport/CHANGELOG.md index 4fb3b8ebca945..adf673e84bb9f 100644 --- a/activesupport/CHANGELOG.md +++ b/activesupport/CHANGELOG.md @@ -1,3 +1,10 @@ +* Include `IPAddr#prefix` when serializing an `IPAddr` using the + `ActiveSupport::MessagePack` serializer. This change is backward and forward + compatible — old payloads can still be read, and new payloads will be + readable by older versions of Rails. + + *Taiki Komaba* + * Add `default:` support for `ActiveSupport::CurrentAttributes.attribute` ```ruby diff --git a/activesupport/lib/active_support/message_pack/extensions.rb b/activesupport/lib/active_support/message_pack/extensions.rb index 3cd7b880a6fd7..3e3ba64cbff38 100644 --- a/activesupport/lib/active_support/message_pack/extensions.rb +++ b/activesupport/lib/active_support/message_pack/extensions.rb @@ -86,8 +86,9 @@ def install(registry) unpacker: URI.method(:parse) registry.register_type 14, IPAddr, - packer: :to_s, - unpacker: :new + packer: method(:write_ipaddr), + unpacker: method(:read_ipaddr), + recursive: true registry.register_type 15, Pathname, packer: :to_s, @@ -221,6 +222,18 @@ def read_set(unpacker) Set.new(unpacker.read) end + def write_ipaddr(ipaddr, packer) + if ipaddr.prefix < 32 || (ipaddr.ipv6? && ipaddr.prefix < 128) + packer.write("#{ipaddr}/#{ipaddr.prefix}") + else + packer.write(ipaddr.to_s) + end + end + + def read_ipaddr(unpacker) + IPAddr.new(unpacker.read) + end + def write_hash_with_indifferent_access(hwia, packer) packer.write(hwia.to_h) end diff --git a/activesupport/test/message_pack/shared_serializer_tests.rb b/activesupport/test/message_pack/shared_serializer_tests.rb index f70e474fb254b..0de324c862843 100644 --- a/activesupport/test/message_pack/shared_serializer_tests.rb +++ b/activesupport/test/message_pack/shared_serializer_tests.rb @@ -127,6 +127,12 @@ module MessagePackSharedSerializerTests test "roundtrips IPAddr" do assert_roundtrip IPAddr.new("127.0.0.1") + assert_roundtrip IPAddr.new("1.1.1.1/16") + assert_equal 16, load(dump(IPAddr.new("1.1.1.1/16"))).prefix + + assert_roundtrip IPAddr.new("::1") + assert_roundtrip IPAddr.new("1:1:1:1:1:1:1:1/64") + assert_equal 64, load(dump(IPAddr.new("1:1:1:1:1:1:1:1/64"))).prefix end test "roundtrips Pathname" do