class Onebox::OpenGraph

Attributes

data[R]

Public Class Methods

new(doc) click to toggle source
# File lib/onebox/open_graph.rb, line 8
def initialize(doc)
  @data = extract(doc)
end

Public Instance Methods

get(attr, length = nil, sanitize = true) click to toggle source
# File lib/onebox/open_graph.rb, line 42
def get(attr, length = nil, sanitize = true)
  return nil if Onebox::Helpers::blank?(data)

  value = data[attr]

  return nil if Onebox::Helpers::blank?(value)

  value = html_entities.decode(value)
  value = Sanitize.fragment(value) if sanitize
  value.strip!
  value = Onebox::Helpers.truncate(value, length) unless length.nil?

  value
end
method_missing(attr, *args, &block) click to toggle source
# File lib/onebox/open_graph.rb, line 26
def method_missing(attr, *args, &block)
  value = get(attr, *args)

  return nil if Onebox::Helpers::blank?(value)

  method_name = attr.to_s
  if method_name.end_with?(*integer_suffixes)
    value.to_i
  elsif method_name.end_with?(*url_suffixes)
    result = Onebox::Helpers.normalize_url_for_output(value)
    result unless Onebox::Helpers::blank?(result)
  else
    value
  end
end
secure_image_url() click to toggle source
# File lib/onebox/open_graph.rb, line 20
def secure_image_url
  secure_url = URI(get(:image))
  secure_url.scheme = 'https'
  secure_url.to_s
end
title() click to toggle source
# File lib/onebox/open_graph.rb, line 12
def title
  get(:title, 80)
end
title_attr() click to toggle source
# File lib/onebox/open_graph.rb, line 16
def title_attr
  !title.nil? ? "title='#{title}'" : ""
end

Private Instance Methods

extract(doc) click to toggle source
# File lib/onebox/open_graph.rb, line 71
def extract(doc)
  return {} if Onebox::Helpers::blank?(doc)

  data = {}

  doc.css('meta').each do |m|
    if (m["property"] && m["property"][/^(?:og|article|product):(.+)$/i]) || (m["name"] && m["name"][/^(?:og|article|product):(.+)$/i])
      value = (m["content"] || m["value"]).to_s
      data[$1.tr('-:', '_').to_sym] ||= value unless Onebox::Helpers::blank?(value)
    end
  end

  # Attempt to retrieve the title from the meta tag
  title_element = doc.at_css('title')
  if title_element && title_element.text
    data[:title] ||= title_element.text unless Onebox::Helpers.blank?(title_element.text)
  end

  data
end
html_entities() click to toggle source
# File lib/onebox/open_graph.rb, line 67
def html_entities
  @html_entities ||= HTMLEntities.new
end
integer_suffixes() click to toggle source
# File lib/onebox/open_graph.rb, line 59
def integer_suffixes
  ['width', 'height']
end
url_suffixes() click to toggle source
# File lib/onebox/open_graph.rb, line 63
def url_suffixes
  ['url', 'image', 'video']
end