Class: HTMLPipeline::NodeFilter::ImageMaxWidthFilter

Inherits:
HTMLPipeline::NodeFilter show all
Defined in:
lib/html_pipeline/node_filter/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.

Constant Summary collapse

SELECTOR =
Selma::Selector.new(match_element: "img")

Instance Attribute Summary

Attributes inherited from HTMLPipeline::NodeFilter

#context

Attributes inherited from Filter

#context, #result

Instance Method Summary collapse

Methods inherited from HTMLPipeline::NodeFilter

call, #html, #initialize, #reset!

Methods inherited from Filter

#base_url, #call, call, #has_ancestor?, #initialize, #needs, #validate

Constructor Details

This class inherits a constructor from HTMLPipeline::NodeFilter

Instance Method Details

#handle_element(element) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/html_pipeline/node_filter/image_max_width_filter.rb', line 18

def handle_element(element)
  # Skip if there's already a style attribute. Not sure how this
  # would happen but we can reconsider it in the future.
  return if element["style"]

  # Bail out if src doesn't look like a valid http url. trying to avoid weird
  # js injection via javascript: urls.
  return if /\Ajavascript/i.match?(element["src"].to_s.strip)

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

  link_image(element) unless has_ancestor?(element, "a")
end


32
33
34
35
36
37
# File 'lib/html_pipeline/node_filter/image_max_width_filter.rb', line 32

def link_image(element)
  link_start = %(<a target="_blank" href="#{element["src"]}">)
  element.before(link_start, as: :html)
  link_end = "</a>"
  element.after(link_end, as: :html)
end

#selectorObject



14
15
16
# File 'lib/html_pipeline/node_filter/image_max_width_filter.rb', line 14

def selector
  SELECTOR
end