Also on twitter ( twitter.com/nutrun )

HMachine

20 odd lines of a dirty hack for a Microformats parser (thanks to open-uri and Hpricot).

%w(rubygems hpricot open-uri).each {|l| require l}
module Microformats
  class Microformat < Struct
    def self.for(uri)
      mf = new
      name = mf.class.name.split('::').last.downcase
      doc = Hpricot(open(uri))
      members.each do |m|
        eval %{
          val = doc%('.#{name} .#{m.gsub('_', '-')}')
          mf.#{m} = val.inner_text.strip if not val.nil?
        }
      end
      mf
    end
    class << self; alias :/ :for end
  end
end

Adding support for microformat specifications can be achieved as:

module Microformats
  class MyFormat < Microformat.new(:x, :y, :z);end
end

Where :x, :y, :z are the Microformat's properties.
As a more concrete example, let's add support for (part of) HReview:

class HReview < Microformat.new(:summary, :fn,
                                :dtreviewed, :description,
                                :rating);end

In action...

include Microformats

hr = HReview.for('http://www.amk.ca/books/h/Velocity_of_Honey')
p hr.fn

# => "The Velocity of Honey: And More Science of Everyday Life"

... or even slicker...

hr = HReview/'http://www.amk.ca/books/h/Velocity_of_Honey'

Comments are closed.