Created
August 2, 2023 21:07
-
-
Save jarednorman/6867d65036af100a094843d292ecb9d1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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