sutty/app/models/metadata_template.rb

91 lines
2.1 KiB
Ruby
Raw Normal View History

2019-08-06 17:54:17 +00:00
# frozen_string_literal: true
# Representa la plantilla de un campo en los metadatos del artículo
#
# TODO: Validar el tipo de valor pasado a value= según el :type
2019-08-13 23:33:57 +00:00
#
# rubocop:disable Metrics/BlockLength
2019-08-06 17:54:17 +00:00
MetadataTemplate = Struct.new(:site, :document, :name, :label, :type,
2019-08-08 18:28:23 +00:00
:value, :help, :required, :errors, :post,
2019-08-07 21:35:37 +00:00
:layout, keyword_init: true) do
include ActionText::ContentHelper
2019-08-06 17:54:17 +00:00
# El valor por defecto
def default_value
raise NotImplementedError
end
# Valores posibles, busca todos los valores actuales en otros
# artículos del mismo sitio
def values
2020-05-23 15:38:03 +00:00
site.everything_of(name, lang: post.try(:lang).try(:value))
2019-08-06 17:54:17 +00:00
end
# Valor actual o por defecto
#
# XXX: No estamos sanitizando la entrada, cada tipo tiene que
# auto-sanitizarse.
2019-08-06 17:54:17 +00:00
def value
self[:value] || document.data.fetch(name.to_s, default_value)
end
# Detecta si el valor está vacío
def empty?
value.blank?
end
# Comprueba si el metadato es válido
def valid?
validate
end
def validate
self.errors = []
errors << I18n.t("metadata.#{type}.cant_be_empty") unless can_be_empty?
errors.empty?
end
2019-08-13 23:33:57 +00:00
def to_param
name
end
# Decide si el metadato se coloca en el front_matter o no
def front_matter?
true
end
2019-08-16 23:25:07 +00:00
def array?
type == 'array'
end
2019-08-22 01:09:29 +00:00
# En caso de que algún campo necesite realizar acciones antes de ser
# guardado
def save
self[:value] = sanitize value
2019-08-22 01:09:29 +00:00
true
end
private
# Si es obligatorio no puede estar vacío
def can_be_empty?
true unless required && empty?
2019-08-06 17:54:17 +00:00
end
# No usamos sanitize_action_text_content porque espera un ActionText
#
# Ver ActionText::ContentHelper#sanitize_action_text_content
def sanitize(string)
return unless string
return string unless string.is_a? String
sanitizer.sanitize(string,
tags: allowed_tags,
2020-03-17 17:49:39 +00:00
attributes: allowed_attributes + %w[data-trix-attachment],
scrubber: scrubber).strip.html_safe
end
2019-08-06 17:54:17 +00:00
end
2019-08-13 23:33:57 +00:00
# rubocop:enable Metrics/BlockLength