Skip to content

Instantly share code, notes, and snippets.

@superfeedr
Created November 5, 2010 22:21
Show Gist options
  • Save superfeedr/664966 to your computer and use it in GitHub Desktop.
Save superfeedr/664966 to your computer and use it in GitHub Desktop.
simple_as_mapper.rb
require 'rubygems'
require 'nokogiri'
require 'yajl'
require 'json'
txt = File.read(ARGV[0])
xml = Nokogiri::XML(txt).root
AS_PREFIX = "http://activitystrea.ms/schema/1.0/"
class Node
def initialize(xml)
@xml = xml
@h = {}
end
def convert
@xml.children.each do |child|
send("on_#{child.name.gsub("-","_")}", child)
end
@h
end
def method_missing(m, *args, &block)
# We should do nothing here :)
end
def on_link(node)
@h[:links] ||= []
@h[:links].push({
:href => node[:href],
:title => node[:title],
:rel => node[:rel],
:type => node[:type]
})
end
def on_title(node)
@h[:title] = node.text
end
def on_id(node)
@h[:id] = node.text
end
def on_published(node)
@h[:postedTime] = node.text
end
def updated(node)
# WTF? TOFIX
end
def on_object_type(node)
@h[:objectType] = node.text.gsub(AS_PREFIX, "")
end
def on_content(node)
@h[:content] = node.text
end
def on_summary(node)
@h[:summary] = node.text
end
def on_author(node)
@h[:actor] ||= Author.new(node).convert
end
def on_id(node)
@h[:id] = node.text
end
end
class Author < Node
def on_name(node)
@h[:displayName] = node.text
end
def on_uri(node)
@h[:permalinkUrl] = node.text
end
def on_email(node)
# Seems like we could ignore it to match the AS spec?
end
def on_link(node)
if node[:type] =~ /image\/./
@h[:image] = {
:url => node[:href]
}
else
super(node)
end
end
end
class ASObject < Node
end
class Entry < Node
def on_point(node)
@h[:latitude], @h[:longitude] = node.text.split(" ")
end
def on_category(node)
@h[:categories] ||= []
@h[:categories].push(node[:term])
end
def on_verb(node)
@h[:verb] = node.text.gsub(AS_PREFIX, "") if node.text =~ /#{AS_PREFIX}/
end
def on_object(node)
@h[:object] ||= ASObject.new(node).convert
end
end
class Feed < Node
def on_entry(node)
@h[:items] ||= []
@h[:items].push Entry.new(node).convert
end
end
puts JSON.pretty_generate(Feed.new(xml).convert)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment