Skip to content

Commit b1ade76

Browse files
committed
Format Date in ISO-8601 explicitly
Fix #644
1 parent 1765bfb commit b1ade76

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

lib/psych/visitors/yaml_tree.rb

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -189,7 +189,8 @@ def visit_Regexp o
189189
end
190190

191191
def visit_Date o
192-
register o, visit_Integer(o.gregorian)
192+
formatted = format_date o
193+
register o, @emitter.scalar(formatted, nil, nil, true, false, Nodes::Scalar::ANY)
193194
end
194195

195196
def visit_DateTime o
@@ -486,6 +487,10 @@ def format_time time, utc = time.utc?
486487
end
487488
end
488489

490+
def format_date date
491+
date.strftime("%Y-%m-%d")
492+
end
493+
489494
def register target, yaml_obj
490495
@st.register target, yaml_obj
491496
yaml_obj

test/psych/test_date_time.rb

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,5 +85,20 @@ def test_alias_with_time
8585
assert_match('&', yaml)
8686
assert_match('*', yaml)
8787
end
88+
89+
def test_overwritten_to_s
90+
pend "Failing on JRuby" if RUBY_PLATFORM =~ /java/
91+
s = Psych.dump(Date.new(2023, 9, 2), permitted_classes: [Date])
92+
assert_separately(%W[-rpsych -rdate - #{s}], "#{<<~"begin;"}\n#{<<~'end;'}")
93+
class Date
94+
undef to_s
95+
def to_s; strftime("%D"); end
96+
end
97+
expected = ARGV.shift
98+
begin;
99+
s = Psych.dump(Date.new(2023, 9, 2), permitted_classes: [Date])
100+
assert_equal(expected, s)
101+
end;
102+
end
88103
end
89104
end

0 commit comments

Comments
 (0)