2022-06-13 11:32:34 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
module Onebox
|
|
|
|
class Normalizer
|
|
|
|
attr_reader :data
|
|
|
|
|
2022-11-24 10:28:21 -05:00
|
|
|
def get(attr, *args)
|
2022-06-13 11:32:34 -04:00
|
|
|
value = data[attr]
|
2022-11-24 10:28:21 -05:00
|
|
|
return if value.blank?
|
|
|
|
return value.map { |v| sanitize_value(v, *args) } if value.is_a?(Array)
|
|
|
|
sanitize_value(value, *args)
|
2022-06-13 11:32:34 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
def method_missing(attr, *args, &block)
|
|
|
|
value = get(attr, *args)
|
|
|
|
|
2023-10-07 13:54:26 -04:00
|
|
|
return nil if value.blank?
|
2022-06-13 11:32:34 -04:00
|
|
|
|
|
|
|
method_name = attr.to_s
|
|
|
|
if method_name.end_with?(*integer_suffixes)
|
|
|
|
value.to_i
|
|
|
|
elsif method_name.end_with?(*url_suffixes)
|
2023-10-07 13:54:26 -04:00
|
|
|
Onebox::Helpers.normalize_url_for_output(value).presence
|
2022-06-13 11:32:34 -04:00
|
|
|
else
|
|
|
|
value
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def integer_suffixes
|
|
|
|
%w[width height]
|
|
|
|
end
|
|
|
|
|
|
|
|
def url_suffixes
|
|
|
|
%w[url image video]
|
|
|
|
end
|
|
|
|
|
|
|
|
def html_entities
|
|
|
|
@html_entities ||= HTMLEntities.new
|
|
|
|
end
|
2022-11-24 10:28:21 -05:00
|
|
|
|
|
|
|
def sanitize_value(value, length = nil, sanitize = true)
|
|
|
|
value = html_entities.decode(value)
|
|
|
|
value = Sanitize.fragment(value) if sanitize
|
|
|
|
value.strip!
|
|
|
|
value = Onebox::Helpers.truncate(value, length) if length
|
|
|
|
value
|
|
|
|
end
|
2022-06-13 11:32:34 -04:00
|
|
|
end
|
|
|
|
end
|