Ruby and Microformats

Jun 19, 2008

Heard about microformats ? Want to know how to consume them within your rails app? It's a suprisingly simple task. But why would you bother? Well lets take a somewhat practical example. What if on your site you wanted to include a list of upcoming events that you were either attending or might be of use to your users? Say for example, events in the UK for the next 30 days

The first thing you need to do, is go grab mofo

sudo gem install mofo

And now include it in your ruby/ruby on rails application:

require 'mofo'

Next, find the URL of the page you want to consume that is exposing it's data as a microformat (read the microformats website for various formats that are available and details on how they are implemented). And within our controller method, we will go and fetch the appropriate information from Upcoming

@events = hCalendar.find ''

And within our view we could do something like the following (ignore the lack of partials and other useful things, this is just for demonstration purposes):


<% @events.each do |event| %>


    <h1><a href="<%event.url%>"><%=event.summary%></a></h1>


    <p><%=event.dtstart.strftime("%d %B")%></p>


<% end %>


Of course, being good little net citizens we should probably also make the list into a microformat too just in case someone else wants to try and consume it from our site, so the addition of a few class attributes and a title tag or two will sort that out:

<ol class="vcalendar">

<% @events.each do |event| %>

  <li class="vevent">

    <h1><a href="<%event.url%>" class="url summary"><%=event.summary%></a></h1>

    <p class="location"><%=event.location%></p>

    <p class="dtstart" title="<%=event.dtstart.strftime("%Y-%m-%d")%>"><%=event.dtstart.strftime("%d %B")%></p>


<% end %>


Keep in mind, the current implementation will send off a request to every time someone loads your page and could seriously harm performance, I'd recommend caching the results either to file or directly into a model/table and then having a process that regularly checks and updates the data at a certain interval.

The possibilities here and endless, and you don't have to consume and re-display but you could create your own mashup for your personal use. Many shopping sites now include review information as a microformat, TripIt makes all of my itineraries available the same way. My recent interest has been spurred on by a site I'm working on where most of the data will be available as a microformat, hopefully letting 3rd parties develop uses for the site that I'd never imagined.

Hi, I'm Glenn! 👋 I'm currently Director of Product @ HashiCorp, and we're hiring! If you'd like to come and work with me and help make Terraform Cloud even more amazing we have multiple positions opening in Product ManagementDesign, and Engineering & Engineering Management across a range of levels (i.e., junior through to senior). Please send in an application ASAP so we can get in touch.