OGP is a minimalist Ruby library that does only one thing: parse Open Graph protocol information. For more information: http://ogp.me.
Add this line to your application’s Gemfile:
gem 'ogp'
And then execute:
$ bundle
Or install it yourself as:
$ gem install ogp
In order to keep OGP very simple, it does not perform any HTTP operations. As such, in this example, Faraday is used to achieve this functionality.
require 'faraday'
require 'ogp'
response = Faraday.get('http://ogp.me')
open_graph = OGP::OpenGraph.new(response.body)
open_graph.title # => "Open Graph protocol"
open_graph.type # => "website"
open_graph.image.url # => "http://ogp.me/logo.png"
open_graph.url # => "http://ogp.me/"
# All open graph tags are additionally stored in a `data` hash so that custom
# open graph tags can still be accessed.
open_graph.data["title"] # => "Open Graph protocol"
By default OGP::OpenGraph.new
validates the presence of the Open Graph attributes title
, type
, image
, url
. If one or more of those are missing it raises a MissingAttributeError
.
To require less or more attributes to be present, supply an array of attribute names with the :required_attributes
option. Examples:
# When you only need title and image
open_graph = OGP::OpenGraph.new(response.body, required_attributes: %w(title image))
# When you require a description, too!
open_graph = OGP::OpenGraph.new(response.body, required_attributes: %w(title type image url description))
Bug reports and pull requests are welcome on GitHub at https://github.com/jcouture/ogp. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the Contributor Covenant code of conduct.
The gem is available as open source under the terms of the MIT License.
The OGP pirate logo is based on this icon by Simon Child, from the Noun Project. Used under a Creative Commons BY 3.0 license.