Class: Seo::ImageMissingSizeFiller

Inherits:
BaseService show all
Defined in:
app/services/seo/image_missing_size_filler.rb

Overview

Service object: image missing size filler.

Defined Under Namespace

Classes: Result

Instance Attribute Summary

Attributes inherited from BaseService

#options

Instance Method Summary collapse

Methods inherited from BaseService

#initialize, #log_debug, #log_error, #log_info, #log_warning, #logger, #tagged_logger

Constructor Details

This class inherits a constructor from BaseService

Instance Method Details

#process(html_fragment) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'app/services/seo/image_missing_size_filler.rb', line 10

def process(html_fragment)
  logger.tagged('Seo::ImageMissingSizeFiller') do
    html_doc = Nokogiri::HTML(html_fragment)
    html_doc.xpath('//img').each do |img|
      if (img_url = img['src'].presence) && (img['width'].blank? || img['height'].blank?)
        # First, check if this is an image from our database
        if (img_id = img['data-image-id'].presence) && (dbimg = Image.find_by(id: img_id))
          if dbimg.attachment_width && dbimg.attachment_height
            img['width'] = dbimg.attachment_width
            img['height'] = dbimg.attachment_height
          end
        else
          # Parse URL and add host for local images
          uri = begin
            Addressable::URI.parse(img_url)
          rescue StandardError
            nil
          end
          if uri && uri.host.blank?
            uri.host = WEB_HOSTNAME_WITHOUT_PORT
            uri.port = APP_PORT_NUMBER unless APP_PORT_NUMBER == 443
            uri.scheme = 'https'
            img_url = uri.to_s
          end

          # Use Vips to read image dimensions
          dimensions = fetch_image_dimensions(img_url)
          if dimensions
            img['width'] = dimensions[:width]
            img['height'] = dimensions[:height]
          end
        end
      end
    end
    html_out = html_doc.at('body')&.inner_html.presence&.html_safe

    Result.new(html_out: html_out)
  end
end