2018-02-13 18:18:20 +01:00
|
|
|
|
class Champs::DateChamp < Champ
|
2023-01-12 17:42:02 +01:00
|
|
|
|
before_validation :convert_to_iso8601, unless: -> { validation_context == :prefill }
|
|
|
|
|
validate :iso_8601
|
2018-06-14 17:41:31 +02:00
|
|
|
|
|
2018-07-25 19:34:06 +02:00
|
|
|
|
def search_terms
|
|
|
|
|
# Text search is pretty useless for dates so we’re not including these champs
|
|
|
|
|
end
|
|
|
|
|
|
2018-06-14 17:41:31 +02:00
|
|
|
|
private
|
|
|
|
|
|
2023-01-12 17:42:02 +01:00
|
|
|
|
def convert_to_iso8601
|
2023-01-26 10:53:47 +01:00
|
|
|
|
return if likely_iso8601_format? && parsable_iso8601?
|
2023-01-12 17:42:02 +01:00
|
|
|
|
|
|
|
|
|
self.value = if /^\d{2}\/\d{2}\/\d{4}$/.match?(value)
|
|
|
|
|
Date.parse(value).iso8601
|
|
|
|
|
else
|
|
|
|
|
nil
|
|
|
|
|
end
|
|
|
|
|
end
|
|
|
|
|
|
|
|
|
|
def iso_8601
|
2023-01-26 10:53:47 +01:00
|
|
|
|
return if parsable_iso8601? || value.blank?
|
2023-01-12 17:42:02 +01:00
|
|
|
|
# i18n-tasks-use t('errors.messages.not_a_date')
|
2023-09-19 11:07:50 +02:00
|
|
|
|
errors.add :date, :not_a_date
|
2023-01-12 17:42:02 +01:00
|
|
|
|
end
|
|
|
|
|
|
2023-01-26 10:53:47 +01:00
|
|
|
|
def likely_iso8601_format?
|
2023-01-12 17:42:02 +01:00
|
|
|
|
/^\d{4}-\d{2}-\d{2}$/.match?(value)
|
2018-06-14 17:41:31 +02:00
|
|
|
|
end
|
2023-01-26 10:53:47 +01:00
|
|
|
|
|
|
|
|
|
def parsable_iso8601?
|
|
|
|
|
Date.parse(value)
|
|
|
|
|
true
|
|
|
|
|
rescue ArgumentError, # case 2023-27-02, out of range
|
|
|
|
|
TypeError # nil
|
|
|
|
|
false
|
|
|
|
|
end
|
2018-02-13 18:18:20 +01:00
|
|
|
|
end
|