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

57 lines
1 KiB
Ruby
Raw Permalink Normal View History

# frozen_string_literal: true
2019-08-08 18:28:23 +00:00
2023-10-06 14:51:58 +00:00
# Atributo de fechas
class MetadataDate < MetadataTemplate
2023-10-06 13:53:19 +00:00
include Metadata::NonIndexableConcern
# La fecha de hoy
#
# @return [Date]
2019-11-07 16:06:40 +00:00
def default_value
2023-10-06 14:51:21 +00:00
super || Date.today
2019-11-07 16:06:40 +00:00
end
2023-10-06 14:51:58 +00:00
def validate
super
begin
sanitize value
rescue Date::Error
errors << I18n.t('metadata.date.invalid_format')
end
errors.empty?
end
2020-12-24 19:13:29 +00:00
# Devuelve una fecha, si no hay ninguna es la fecha de hoy.
#
# @return [Date]
2023-10-06 14:51:58 +00:00
def save
return true unless changed?
2023-10-06 14:51:58 +00:00
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
2019-08-08 18:28:23 +00:00
end