Skip to content

Instantly share code, notes, and snippets.

@leeky
Created September 23, 2024 09:06
Show Gist options
  • Save leeky/b7dfe4c0b0fa050688db0fbc2ce1f774 to your computer and use it in GitHub Desktop.
Save leeky/b7dfe4c0b0fa050688db0fbc2ce1f774 to your computer and use it in GitHub Desktop.
Invalid date handling
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
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