Sha256: f459f956a15103b1ba16726afe3de4d0c35d9ab6019190f5b10746073748d765

Contents?: true

Size: 903 Bytes

Versions: 1

Compression:

Stored size: 903 Bytes

Contents

require 'html_pipeline'
require "addressable/uri"

# SEE: https://github.com/increments/qiita-markdown/blob/master/lib/qiita/markdown/filters/external_link.rb
class HTMLPipeline
  class ExternalLinkFilter < NodeFilter
    SELECTOR = Selma::Selector.new(match_element: %(a[href^="http"]))

    def selector
      SELECTOR
    end

    def handle_element(element)
      return unless element["href"]

      href = element["href"].strip
      href_host = host_of(href)
      return unless href_host

      if href_host != hostname
        element["rel"] = "nofollow noopener"
        element["target"] = "_blank"
      end
    end

    private

    def host_of(url)
      uri = Addressable::URI.parse(url)
      uri.host
    rescue Addressable::URI::InvalidURIError
      nil
    end

    def hostname
      context[:hostname] || raise("Missing context :hostname for #{self.class.name}")
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
html-pipeline-external_link-1.0.0 lib/html/pipeline/external_link/filter.rb