Class: HTML::Pipeline::ImageMaxWidthFilter

Inherits:
Filter
  • Object
show all
Defined in:
lib/html/pipeline_plus/image_max_width_filter.rb

Overview

This filter rewrites image tags with a max-width inline style and also wraps the image in an <a> tag that causes the full size image to be opened in a new tab.

The max-width inline styles are especially useful in HTML email which don’t use a global stylesheets.

Instance Attribute Summary

Attributes inherited from Filter

#context, #result

Instance Method Summary collapse

Methods inherited from Filter

#base_url, call, #current_user, #doc, #has_ancestor?, #html, #initialize, #needs, #parse_html, #repository, to_document, to_html, #validate

Constructor Details

This class inherits a constructor from HTML::Pipeline::Filter

Instance Method Details

#callObject



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/html/pipeline_plus/image_max_width_filter.rb', line 10

def call
  doc.search('img').each do |element|
    # Skip if there's already a style attribute. Not sure how this
    # would happen but we can reconsider it in the future.
    next if element['style']

    # Bail out if src doesn't look like a valid http url. trying to avoid weird
    # js injection via javascript: urls.
    next if element['src'].to_s.strip =~ /\Ajavascript/i

    element['style'] = 'max-width:100%;'

    link_image element unless has_ancestor?(element, %w[a])
  end

  doc
end


28
29
30
31
32
# File 'lib/html/pipeline_plus/image_max_width_filter.rb', line 28

def link_image(element)
  link = doc.document.create_element('a', href: element['src'], target: '_blank')
  link.add_child(element.dup)
  element.replace(link)
end