Sha256: e42c5be8c35a5dfc084ad926e10b6a2c3ca402870ba024385fadc87d32e61b2a

Contents?: true

Size: 1.77 KB

Versions: 48

Compression:

Stored size: 1.77 KB

Contents

module Onebox
  class Preview
    attr_reader :cache

    WEB_EXCEPTIONS ||= [Net::HTTPServerException, OpenURI::HTTPError, Timeout::Error, Net::HTTPError, Errno::ECONNREFUSED]

    def initialize(link, parameters = Onebox.options)
      @url = link
      @options = parameters
      @cache = options.cache
      @engine_class = Matcher.new(@url).oneboxed
    end

    def to_s
      return "" unless engine
      sanitize process_html engine_html
    rescue *WEB_EXCEPTIONS
      ""
    end

    def placeholder_html
      return "" unless engine
      sanitize process_html engine.placeholder_html
    rescue *WEB_EXCEPTIONS
      ""
    end

    def options
      OpenStruct.new(@options)
    end

    private

      def engine_html
        engine.to_html
      end

      def process_html(html)
        return "" unless html

        if @options[:max_width]
          doc = Nokogiri::HTML::fragment(html)
          if doc
            doc.css('[width]').each do |e|
              width = e['width'].to_i

              if width > @options[:max_width]
                height = e['height'].to_i
                if (height > 0)
                  ratio = (height.to_f / width.to_f)
                  e['height'] = (@options[:max_width] * ratio).floor
                end
                e['width'] = @options[:max_width]
              end
            end
            return doc.to_html
          end
        end

        html
      end

      def sanitize(html)
        Sanitize.fragment(html, @options[:sanitize_config] || Sanitize::Config::ONEBOX)
      end

      def engine
        return nil unless @engine_class
        return @engine if @engine

        @engine = @engine_class.new(@url, cache)
        @engine.options = @options
        @engine
      end

      class InvalidURI < StandardError; end
  end
end

Version data entries

48 entries across 48 versions & 1 rubygems

Version Path
onebox-1.8.39 lib/onebox/preview.rb
onebox-1.8.38 lib/onebox/preview.rb
onebox-1.8.36 lib/onebox/preview.rb
onebox-1.8.35 lib/onebox/preview.rb
onebox-1.8.34 lib/onebox/preview.rb
onebox-1.8.33 lib/onebox/preview.rb
onebox-1.8.32 lib/onebox/preview.rb
onebox-1.8.31 lib/onebox/preview.rb
onebox-1.8.30 lib/onebox/preview.rb
onebox-1.8.29 lib/onebox/preview.rb
onebox-1.8.28 lib/onebox/preview.rb
onebox-1.8.27 lib/onebox/preview.rb
onebox-1.8.26 lib/onebox/preview.rb
onebox-1.8.25 lib/onebox/preview.rb
onebox-1.8.24 lib/onebox/preview.rb
onebox-1.8.23 lib/onebox/preview.rb
onebox-1.8.22 lib/onebox/preview.rb
onebox-1.8.21 lib/onebox/preview.rb
onebox-1.8.20 lib/onebox/preview.rb
onebox-1.8.19 lib/onebox/preview.rb