Created
September 23, 2024 09:06
-
-
Save leeky/b7dfe4c0b0fa050688db0fbc2ce1f774 to your computer and use it in GitHub Desktop.
Invalid date handling
This file contains hidden or 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
module DateErrorHandling | |
extend ActiveSupport::Concern | |
INVALID_DATE = Date.new(9999, 1, 1).freeze | |
# This method can be used to safely parse a date input, otherwise a parse error | |
# can cause a crash, rather than simply an error message. It should be used in | |
# collaboration with model validation, and to do that you can use the `on_error` | |
# param to specify what should be returned on error. If your field is required | |
# (i.e., allow_blank: false) you can call this with `on_error: nil` and validation | |
# will fail as this is nil. If this field is optional, you should then use | |
# `on_error: INVALID_DATE` and then add a custom validation to your model which | |
# makes sure this field is not INVALID_DATE (and if it is, forces it to be nil | |
# after adding the error to the array so the field is reset for the user). | |
def safe_parse_date(date, on_error:) | |
return date unless date.is_a?(Hash) | |
begin | |
Date.new(date[1], date[2], date[3]) | |
rescue Date::Error | |
on_error | |
end | |
end | |
end |
This file contains hidden or 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
class YourModelCLass | |
include DateErrorHandling | |
attribute :date_of_hearing, :date | |
validates :date_of_hearing, ... | |
validate :invalid_date | |
def date_of_hearing=(date) | |
super(safe_parse_date(date, on_error: INVALID_DATE)) | |
end | |
... | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment