Our application previously defined the default date format as DD/MM/YYYY in config/application.rb like so:
Date::DATE_FORMATS[:default] = '%d/%m/%Y'
This worked as expected in Rails 6.1, but after upgrading to Rails 7.0 it now appears to be ignored by .to_s:
Loading development environment (Rails 7.0.2.2)
3.0.1 :001 > Date::DATE_FORMATS[:default]
=> "%d/%m/%Y"
3.0.1 :002 > Date.new(2022, 12, 31).to_s
=> "2022-12-31"
3.0.1 :003 > Date.new(2022, 12, 31).to_fs
=> "31/12/2022"
How can I have .to_s implement this behaviour in Rails 7.0+?
Bear in mind, config.active_support.disable_to_s_conversion doesn't restore the original functionality of to_s on a date. Your dates will not hit the default formatter you have configured.
I'm not sure if any of this is intentional.
You have two options to fix this:
.to_fs. This is probably the more correct way to fix this..to_s method on a date because going to over 9000 different locations to add .to_fs to each date display in your code is just too much for you to think about right now../config/initializers/date_format_fix.rb
require "date"
class Date
def to_s(format = :default)
if formatter = DATE_FORMATS[format]
if formatter.respond_to?(:call)
formatter.call(self).to_s
else
strftime(formatter)
end
else
to_default_s
end
end
end
The same can be done with Time and DateTime.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With