Sha256: 1d3bc33603fbe721c0ef4ba5ba9dff285b7c8feda014af9e2d4fac994cb0c22e

Contents?: true

Size: 944 Bytes

Versions: 1

Compression:

Stored size: 944 Bytes

Contents

require 'html/pipeline'
require "addressable/uri"

# SEE: https://github.com/increments/qiita-markdown/blob/master/lib/qiita/markdown/filters/external_link.rb
module HTML
  class Pipeline
    class ExternalLinkFilter < Filter
      def call
          doc.search("a").each do |anchor|
            next unless anchor["href"]
            href = anchor["href"].strip
            href_host = host_of(href)
            next unless href_host
            if href_host != hostname
              anchor["rel"] = "nofollow noopener"
              anchor["target"] = "_blank"
            end
          end

          doc
        end

        def validate
          needs :hostname
        end

        private

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

        def hostname
          context[:hostname]
        end

    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

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