class Onebox::Preview

Public Class Methods

new(url, options = Onebox.options) click to toggle source
# File lib/onebox/preview.rb, line 9
def initialize(url, options = Onebox.options)
  @url = url
  @options = options.dup

  allowed_origins = @options[:allowed_iframe_origins] || Onebox::Engine.all_iframe_origins
  @options[:allowed_iframe_regexes] = Engine.origins_to_regexes(allowed_origins)

  @engine_class = Matcher.new(@url, @options).oneboxed
end

Public Instance Methods

data() click to toggle source
# File lib/onebox/preview.rb, line 38
def data
  return {} unless engine
  engine.data
end
errors() click to toggle source
# File lib/onebox/preview.rb, line 33
def errors
  return {} unless engine
  engine.errors
end
options() click to toggle source
# File lib/onebox/preview.rb, line 43
def options
  OpenStruct.new(@options)
end
placeholder_html() click to toggle source
# File lib/onebox/preview.rb, line 26
def placeholder_html
  return "" unless engine
  sanitize process_html engine.placeholder_html
rescue *WEB_EXCEPTIONS
  ""
end
to_s() click to toggle source
# File lib/onebox/preview.rb, line 19
def to_s
  return "" unless engine
  sanitize process_html engine_html
rescue *WEB_EXCEPTIONS
  ""
end

Private Instance Methods

engine() click to toggle source
# File lib/onebox/preview.rb, line 85
def engine
  return nil unless @engine_class
  return @engine if defined?(@engine)

  @engine = @engine_class.new(@url)
  @engine.options = @options
  @engine
end
engine_html() click to toggle source
# File lib/onebox/preview.rb, line 49
def engine_html
  engine.to_html
end
process_html(html) click to toggle source
# File lib/onebox/preview.rb, line 53
def process_html(html)
  return "" unless html

  if @options[:max_width]
    doc = Nokogiri::HTML5::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
sanitize(html) click to toggle source
# File lib/onebox/preview.rb, line 78
def sanitize(html)
  config = @options[:sanitize_config] || Sanitize::Config::ONEBOX
  config = config.merge(allowed_iframe_regexes: @options[:allowed_iframe_regexes])

  Sanitize.fragment(html, config)
end