Created
July 21, 2017 00:57
-
-
Save coreyward/6a26421d3e994b2b7b12dfffa951b909 to your computer and use it in GitHub Desktop.
Copy-pasteable Rails initializer that will handle date to string conversion and parsing (with output as MM/DD/YYYY by default)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Date::DATE_FORMATS[:default] = "%m/%d/%Y" | |
module FixDateFormatting | |
class EasyDate < ActiveRecord::Type::Date | |
def cast_value(value) | |
default = super | |
parsed = Chronic.parse(value)&.to_date if value.is_a?(String) | |
parsed || default | |
end | |
end | |
def inherited(subclass) | |
super | |
date_attributes = subclass.attribute_types.select { |_, type| ActiveRecord::Type::Date === type } | |
date_attributes.each do |name, _type| | |
subclass.attribute name, EasyDate.new | |
end | |
end | |
end | |
Rails.application.config.to_prepare do | |
ApplicationRecord.extend(FixDateFormatting) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment