Use YAML.load_tags/dump_tags to prevent deprecation warnings

The default behavior of the Psych gem for Ruby classes is to call the
`name` method to generate a tag for encoding. However this causes a
stream of deprecation warnings whenever ActiveSupport::TimeWithZone
instances are encoded into YAML. By utilising the load_tags/dump_tags
configuration we can prevent Psych from calling the `name` method and
thereby prevent the triggering of the deprecation warnings.
This commit is contained in:
Andrew White 2021-04-07 23:15:12 +01:00
parent 57cbf4136f
commit db9ba18659
No known key found for this signature in database
GPG Key ID: 7E83729F16B086CF
3 changed files with 13 additions and 3 deletions

View File

@ -1,5 +1,7 @@
# frozen_string_literal: true
require "yaml"
require "active_support/duration"
require "active_support/values/time_zone"
require "active_support/core_ext/object/acts_like"
@ -182,7 +184,6 @@ module ActiveSupport
end
def encode_with(coder) #:nodoc:
coder.tag = "!ruby/object:ActiveSupport::TimeWithZone"
coder.map = { "utc" => utc, "zone" => time_zone, "time" => time }
end
@ -588,3 +589,8 @@ module ActiveSupport
end
end
end
# These prevent Psych from calling `ActiveSupport::TimeWithZone.name`
# and triggering the deprecation warning about the change in Rails 7.1.
YAML.load_tags["!ruby/object:ActiveSupport::TimeWithZone"] = "ActiveSupport::TimeWithZone"
YAML.dump_tags[ActiveSupport::TimeWithZone] = "!ruby/object:ActiveSupport::TimeWithZone"

View File

@ -585,6 +585,7 @@ class HashToXmlTest < ActiveSupport::TestCase
end
def test_timezoned_attributes
# TODO: Remove assertion in Rails 7.1 and add ActiveSupport::TimeWithZone to XML type mapping
assert_deprecated("ActiveSupport::TimeWithZone.name has been deprecated") do
xml = {
created_at: Time.utc(1999, 2, 2),

View File

@ -186,7 +186,8 @@ class TimeWithZoneTest < ActiveSupport::TestCase
time: 1999-12-31 19:00:00.000000000 Z
EOF
assert_deprecated("ActiveSupport::TimeWithZone.name has been deprecated") do
# TODO: Remove assertion in Rails 7.1
assert_not_deprecated do
assert_equal(yaml, @twz.to_yaml)
end
end
@ -201,7 +202,8 @@ class TimeWithZoneTest < ActiveSupport::TestCase
time: 1999-12-31 19:00:00.000000000 Z
EOF
assert_deprecated("ActiveSupport::TimeWithZone.name has been deprecated") do
# TODO: Remove assertion in Rails 7.1
assert_not_deprecated do
assert_equal(yaml, { "twz" => @twz }.to_yaml)
end
end
@ -571,6 +573,7 @@ class TimeWithZoneTest < ActiveSupport::TestCase
end
def test_class_name
# TODO: Remove assertion in Rails 7.1 and change expected value
assert_deprecated("ActiveSupport::TimeWithZone.name has been deprecated") do
assert_equal "Time", ActiveSupport::TimeWithZone.name
end