From 2b72e4affe7fd5293b84a62d754663ea2dcd2009 Mon Sep 17 00:00:00 2001 From: f Date: Fri, 6 Oct 2023 11:51:58 -0300 Subject: [PATCH] =?UTF-8?q?refactor:=20validaci=C3=B3n=20de=20fecha?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/models/metadata_date.rb | 45 ++++++++++++++++++++++++++++++------- 1 file changed, 37 insertions(+), 8 deletions(-) diff --git a/app/models/metadata_date.rb b/app/models/metadata_date.rb index 13f2ec5c..9c9a5d38 100644 --- a/app/models/metadata_date.rb +++ b/app/models/metadata_date.rb @@ -1,5 +1,6 @@ # frozen_string_literal: true +# Atributo de fechas class MetadataDate < MetadataTemplate include Metadata::NonIndexableConcern @@ -10,18 +11,46 @@ class MetadataDate < MetadataTemplate super || Date.today end + def validate + super + + begin + sanitize value + rescue Date::Error + errors << I18n.t('metadata.date.invalid_format') + end + + errors.empty? + end + # Devuelve una fecha, si no hay ninguna es la fecha de hoy. # # @return [Date] - def value - return self[:value] if self[:value].is_a? Date - return self[:value] if self[:value].is_a? Time - return document_value || default_value unless self[:value] + def save + return true unless changed? - begin - self[:value] = Date.parse self[:value] - rescue ArgumentError, TypeError - default_value + self[:value] = sanitize(self[:value]) || document_value || default_value + + true + end + + private + + # Devuelve una fecha o nada. Sigue el formato de fechas de Jekyll, + # con lo que no acepta fechas en el futuro lejano. + # + # @param :value [Any] + # @return [Date,nil] + def sanitize(value) + case value + when Date then value + when Time then value.to_date + when String + value = super(value) + + raise Date::Error unless /\A\d{2,4}-\d{1,2}-\d{1,2}\z/ =~ value + + Date.iso8601(value) end end end