sutty/app/models/metadata_document_date.rb
f c3a8b2401c estandarizar la forma de obtener el valor de los documentos
teníamos dos métodos que hacían lo mismo y generaban conflictos al
obtener el valor por defecto de los arrays cuando no eran arrays.
2021-06-16 11:35:37 -03:00

65 lines
1.3 KiB
Ruby

# frozen_string_literal: true
# Maneja la fecha del document
class MetadataDocumentDate < MetadataTemplate
# La fecha por defecto es ahora!
def default_value
Date.today.to_time
end
# @return [Time]
def document_value
return nil if post.new?
document.date
end
def indexable?
true && !private?
end
# Siempre es obligatorio
def required
true
end
def validate
super
errors << I18n.t('metadata.date.invalid_format') unless valid_format?
errors.empty?
end
# El valor puede ser un Date, Time o una String en el formato
# "yyyy-mm-dd"
#
# XXX: Date.iso8601 acepta fechas en el futuro lejano, como 20000,
# pero Jekyll las limita a cuatro cifras, así que vamos a mantener
# eso.
#
# @see {https://github.com/jekyll/jekyll/blob/master/lib/jekyll/document.rb#L15}
def value
self[:value] =
case self[:value]
when String
begin
Date.iso8601(self[:value]).to_time
rescue Date::Error
document_value || default_value
end
else
self[:value] || document_value || default_value
end
end
private
def valid_format?
return true if self[:value].is_a?(Time)
@valid_format_re ||= /\A\d{2,4}-\d{1,2}-\d{1,2}\z/
@valid_format_re =~ self[:value].to_s
end
end