Skip to content

Instantly share code, notes, and snippets.

@jgarber623
Last active September 1, 2022 02:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jgarber623/2880c9c5cce7220d3178cdc6ee3d67a3 to your computer and use it in GitHub Desktop.
Save jgarber623/2880c9c5cce7220d3178cdc6ee3d67a3 to your computer and use it in GitHub Desktop.
An example Ruby class implementing the microformats2 "representative h-card" parsing algorithm using MicroMicro.
# frozen_string_literal: true
class RepresentativeHCardParser
# @param document [MicroMicro::Document]
# @param canonical_url [String]
def initialize(document, canonical_url)
@document = document
@canonical_url = canonical_url
end
# @return [MicroMicro::Item, nil]
def h_card
@h_card ||=
h_card_with_uid_and_url_properties_matching_page_url \
|| h_card_with_url_property_matching_page_url \
|| h_card_with_url_property_matching_rel_me_relationship
end
private
attr_reader :canonical_url, :document
def h_card_with_uid_and_url_properties_matching_page_url
document.items.find_by do |item|
item.properties.find_by(name: 'uid', value: canonical_url) \
&& item.properties.find_by(name: 'url', value: canonical_url)
end
end
def h_card_with_url_property_matching_page_url
rel_urls = document.relationships.where(rels: ['me']).urls
document.items.find_by do |item|
item.properties.find_by(name: 'url', value: rel_urls)
end
end
def h_card_with_url_property_matching_rel_me_relationship
return unless document.items.where(types: 'h-card').one?
document.items.find_by do |item|
item.types.include?('h-card') \
&& item.properties.find_by(name: 'url', value: canonical_url)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment