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-12-28 15:37:20 +01:00
|
|
|
|
def to_s
|
2019-11-25 14:39:42 +01:00
|
|
|
|
value.present? ? I18n.l(Time.zone.parse(value), format: '%d %B %Y') : ""
|
2023-04-05 12:16:52 +02:00
|
|
|
|
rescue ArgumentError
|
|
|
|
|
value.presence || "" # old dossiers can have not parseable dates
|
2018-12-28 15:37:20 +01:00
|
|
|
|
end
|
|
|
|
|
|
2024-04-02 17:05:44 +02:00
|
|
|
|
def for_tag(path = :value)
|
|
|
|
|
to_s if path == :value
|
|
|
|
|
end
|
2019-09-11 16:04:42 +02:00
|
|
|
|
|
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
|