Skip to content

Instantly share code, notes, and snippets.

@jarednorman
Created August 2, 2023 21:07
Show Gist options
  • Save jarednorman/6867d65036af100a094843d292ecb9d1 to your computer and use it in GitHub Desktop.
Save jarednorman/6867d65036af100a094843d292ecb9d1 to your computer and use it in GitHub Desktop.
module OpenGraph
class << self
def fetch_data(url)
html = Nokogiri::HTML(body(url))
{
title: find_meta("og:title", html) || html.title.presence,
description: find_meta("og:description", html),
image: find_meta("og:image", html),
site_name: find_meta("og:site_name", html)
}
end
private
def body(url)
Faraday.new(url: url) do |faraday|
faraday.use FaradayMiddleware::FollowRedirects
faraday.use :cookie_jar
faraday.adapter Faraday.default_adapter
end.get.body
end
def find_meta(field, html)
html.xpath("//meta[@property='#{field}']").each.map { |meta|
meta.attribute("content")&.value
}.reverse.find(&:presence)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment