-
Notifications
You must be signed in to change notification settings - Fork 205
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
YAML.dump(date) generates warnings with Rails 7.0.7+ #644
Comments
Worse, if you override Here's an initializer patch for both issues, for a codebase where someone changed # frozen_string_literal: true
# NOTE: Overriding Date::DATE_FORMATS[:default] breaks YAML serialization of Date values.
date = Date.today
# Check and patch YAML serialization of Date values, if necessary.
unless ActiveSupport::Deprecation.silence { YAML.dump(date) } == "--- #{date.strftime('%F')}\n"
# Override format and apply https://github.com/ruby/psych/pull/573 too.
Psych::Visitors::YAMLTree.class_exec do
# :reek:UncommunicativeMethodName and :reek:UncommunicativeParameterName are irrelevant here.
def visit_Date(o) # rubocop:disable Naming/MethodName
formatted = o.gregorian.strftime("%F")
register(o, @emitter.scalar(formatted, nil, nil, true, false, ::Psych::Nodes::Scalar::ANY))
end
end
end
# Check YAML deserialization of the old overriden format, and patch if necessary.
unless YAML.unsafe_load("--- #{date.strftime('%m/%d/%Y')}\n") == date
# Parse the Date strings that we used to generate before the above patch.
Psych::ScalarScanner.prepend(
Module.new do
def tokenize(string)
return nil if string.empty?
if string.match?(/^(?:1[012]|0\d|\d)\/(?:[12]\d|3[01]|0\d|\d)\/\d{4}$/)
# US format date
require "date"
begin
class_loader.date.strptime(string, "%m/%d/%Y", ::Date::GREGORIAN)
rescue ArgumentError
string
end
else
super
end
end
end
)
end This patch works on the version of Psych in Ruby 3.1 as well. It does apply the #573 Gregorian date fix to |
Psych serializes Date values with
to_s
, and just assumes thatto_s
generates ISO-8601 format dates. This is a little presumptuous of Psych, in my opinion, given that ActiveSupport in Rails overridesto_s
with a method that can return strings in different formats.It sound be better for Psych to serialize Date values with
strftime('%F')
rather thanto_s
, so it's less likely to break.The text was updated successfully, but these errors were encountered: