Sha256: ef9bf0105e29d05ed5a3cc787d8838a66a37bfa4d322639961f543b50e5dbba4

Contents?: true

Size: 1.31 KB

Versions: 1

Compression:

Stored size: 1.31 KB

Contents

require 'html/pipeline'
require 'uri'
require 'net/http'
require 'json'

module HTML
  class Pipeline
    # HTML Filter for converting flickr's link into linkable image
    #
    # Context options:
    #   :flickr_maxwidth, flickr_minheight - representing maxwidth and maxheight in oembed format's params.
    #   :flickr_link_attr - HTML attributes for the link that will be generated

    class FlickrFilter < TextFilter
      def call
        regex = %r{(=")*(https?:\/\/(www\.)?flickr\.com\/photos\/[^\s<]*)}
        uri = URI("https://www.flickr.com/services/oembed")

        link_attr = context[:flickr_link_attr] || ""

        @text.gsub(regex) do |match|
          if $1.nil?
            params = {
              url: match,
              format: :json,
              maxwidth: max_value(:width),
              maxheight: max_value(:height)
            }

            uri.query = URI.encode_www_form(params)

            response = JSON.parse(Net::HTTP.get(uri))

            %{<a href="#{match}" #{link_attr}><img src="#{response["url"]}" alt="#{response["title"]}" title="#{response["title"]}" /></a>}
          else
            match
          end
        end
      end

      private

      def max_value(attr)
        value = context["flickr_max#{attr}".to_sym]
        value.to_i >= 0 ? value.to_i : 0
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
html-pipeline-flickr-0.1.1 lib/html/pipeline/flickr/flickr_filter.rb