5
0
Fork 0
mirror of https://0xacab.org/sutty/sutty synced 2024-11-24 14:26:22 +00:00

refactor: validación de fecha

This commit is contained in:
f 2023-10-06 11:51:58 -03:00
parent 230beb2cda
commit 2b72e4affe
No known key found for this signature in database

View file

@ -1,5 +1,6 @@
# frozen_string_literal: true # frozen_string_literal: true
# Atributo de fechas
class MetadataDate < MetadataTemplate class MetadataDate < MetadataTemplate
include Metadata::NonIndexableConcern include Metadata::NonIndexableConcern
@ -10,18 +11,46 @@ class MetadataDate < MetadataTemplate
super || Date.today super || Date.today
end 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. # Devuelve una fecha, si no hay ninguna es la fecha de hoy.
# #
# @return [Date] # @return [Date]
def value def save
return self[:value] if self[:value].is_a? Date return true unless changed?
return self[:value] if self[:value].is_a? Time
return document_value || default_value unless self[:value]
begin self[:value] = sanitize(self[:value]) || document_value || default_value
self[:value] = Date.parse self[:value]
rescue ArgumentError, TypeError true
default_value 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 end
end end