sutty/app/models/metadata_template.rb

169 lines
3.8 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
#
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
2020-10-04 01:32:52 +00:00
attr_reader :value_was
def value=(new_value)
@value_was = value
self[:value] = new_value
end
def changed?
!value_was.nil? && value_was != value
end
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-10-04 00:32:32 +00:00
site.everything_of(name, lang: post&.lang&.value)
2019-08-06 17:54:17 +00:00
end
# Valor actual o por defecto. Al memoizarlo podemos modificarlo
# usando otros métodos que el de asignación.
2019-08-06 17:54:17 +00:00
def value
2020-08-20 23:38:31 +00:00
self[:value] ||= if private?
decrypt document.data.fetch(name.to_s, default_value)
else
document.data.fetch(name.to_s, default_value)
end
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 = []
2020-07-02 14:26:00 +00:00
errors << I18n.t('metadata.cant_be_empty') unless can_be_empty?
errors.empty?
end
# Usa el valor por defecto para generar el formato de StrongParam
# necesario.
#
# @return [Symbol,Hash]
2019-08-13 23:33:57 +00:00
def to_param
case default_value
when Hash then { name => default_value.keys.map(&:to_sym) }
when Array then { name => [] }
else name
end
2019-08-13 23:33:57 +00:00
end
def to_s
value.to_s
end
2019-08-13 23:33:57 +00:00
# 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
2020-08-20 23:38:31 +00:00
self[:value] = encrypt(value) if private?
2019-08-22 01:09:29 +00:00
true
end
2020-07-22 23:35:43 +00:00
def related_posts?
false
end
def related_methods
raise NotImplementedError
end
2020-08-20 23:38:31 +00:00
# Determina si el campo es privado y debería ser cifrado
def private?
!!layout.metadata.dig(name, 'private')
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 if string.nil?
return string unless string.is_a? String
2020-08-15 14:58:28 +00:00
sanitizer.sanitize(string.tr("\r", ''),
tags: allowed_tags,
2020-11-14 15:10:55 +00:00
attributes: allowed_attributes,
scrubber: scrubber).strip.html_safe
2020-11-16 16:09:04 +00:00
end
2020-11-14 21:02:30 +00:00
def sanitizer
@sanitizer ||= Rails::Html::Sanitizer.safe_list_sanitizer.new
end
def allowed_attributes
2020-11-16 16:09:04 +00:00
@allowed_attributes ||= %w[style src alt controls data-align].freeze
2020-11-14 21:02:30 +00:00
end
def allowed_tags
2020-11-16 16:09:04 +00:00
@allowed_tags ||= %w[strong em del u mark p h1 h2 h3 h4 h5 h6 ul ol li img iframe audio video div].freeze
end
2020-08-20 23:38:31 +00:00
# Decifra el valor
#
# XXX: Otros tipos de valores necesitan implementar su propio método
# de decifrado (Array).
def decrypt(value)
return value if value.blank?
box.decrypt_str value.to_s
rescue Lockbox::DecryptionError => e
ExceptionNotifier.notify_exception(e)
I18n.t('lockbox.help.decryption_error')
end
# Cifra el valor.
#
# XXX: Otros tipos de valores necesitan implementar su propio método
# de cifrado (Array).
def encrypt(value)
box.encrypt value.to_s
end
# Genera una lockbox a partir de la llave privada del sitio
#
# @return [Lockbox]
def box
@box ||= Lockbox.new key: site.private_key, padding: true, encode: true
end
2019-08-06 17:54:17 +00:00
end