October 25th, 2009 // 12:21 am

OhEmbedr: Embedding videos and images with oEmbed in Ruby

Supported Features

While working on the rewrite of my simple bookmarking service, Picomarks, I needed the capability to easily embed content from video sites like YouTube and Vimeo and image sharing sites like Flickr.

Originally I hacked together some code that would generate a YouTube embed from a YouTube video url before realising that I didn’t want to do this for five or six sites. So I searched around and came across the oEmbed standard, created by Leah Culver and others while they were developing Pownce. oEmbed is a super simple way to get the embed code for all sorts of content including videos and images. For example if I found a cool image on flickr. To get the embed code (which is a ridiculous process on flickr without oEmbed) I make a simple HTTP GET request to Flickr’s oEmbed API.

http://www.flickr.com/services/oembed?url=http://www.flickr.com/photos/xdjio/226228060/&format=json

Flickr responds with an oEmbed response which we requested to be in json.

{
    "version" : "1.0",
    "type" : "photo",
    "title" : "Wasteland",
    "author_name" : "xdjio",
    "author_url" : "http://www.flickr.com/photos/xdjio/",
    "cache_age" : 3600,
    "provider_name" : "Flickr",
    "provider_url" : "http://www.flickr.com/",
    "width" : "500",
    "height" : "336",
    "url" : "http://farm1.static.flickr.com/64/226228060_c88ba6cf6b.jpg"
}

Super simple, right? So I started looking for a way to do this in ruby and I found the ruby-oembed library on GitHub, there was no documentation; so I made my own library, OhEmbedr.

To install just install the gem:

# If you don't have gemcutters in your gem sources already
gem sources -a http://gemcutter.org
 
# Then just gem install
gem install ohembedr

Then to use OhEmbedr is just as easy:

require 'rubygems'
require 'ohembedr'
 
begin
    o = OhEmbedr::OhEmbedr.new(:url => "http://vimeo.com/6382511", 
        :maxwidth => 600)
    embed_data = o.gets
rescue OhEmbedr::UnsupportedError => error
    # URL not supported
end

We wrap it in a begin rescue block because OhEmbedr will raise an OhEmbedr::UnsupportedError if it encounters a URL which isn’t in its providers list, meaning we can pass any url to OhEmbedr and if this exception is raised we know that this url can’t be embedded by oEmbed. Currently the following providers are supported:

  • YouTube
  • Vimeo
  • Flickr
  • Qik
  • Revision 3
  • Viddler
  • Hulu

I do wish more people would adopt oEmbed, the idea of having a standard API for embedding data is really nice. Of course there are a few problems with oEmbed for example having to dig around on the provider site to find the oEmbed API URL but I don’t see anyone suggesting anything better.

So check out the OhEmbedr source on GitHub or its gemcutter page.

Wonderful image from the brilliant xkcd.