Skip to content

Instantly share code, notes, and snippets.

@jaigouk
Forked from mattetti/gist:254801
Created December 12, 2009 14:53
Show Gist options
  • Save jaigouk/254905 to your computer and use it in GitHub Desktop.
Save jaigouk/254905 to your computer and use it in GitHub Desktop.
framework 'Cocoa'
# Documentation for delegates:
# http://developer.apple.com/mac/library/documentation/cocoa/reference/NSXMLParserDelegate_Protocol/Reference/Reference.html
class RSSParser
attr_accessor :parser, :xml_url, :doc
def initialize(xml_url)
@xml_url = xml_url
NSApplication.sharedApplication.delegate = self
url = NSURL.alloc.initWithString(xml_url)
@parser = NSXMLParser.alloc.initWithContentsOfURL(url)
@parser.shouldProcessNamespaces = true
@parser.delegate = self
@items = []
end
class RSSItem
attr_accessor :title, :description, :link, :guid, :pubDate, :enclosure
def initialize
@title, @description, @link, @pubDate, @guid = '', '', '', '', ''
end
end
def parse(&block)
@block = block
puts "Parsing #{xml_url}"
@parser.parse
end
def block_while_parsing(&block)
@parsed = false
parse(&block)
NSRunLoop.currentRunLoop.runUntilDate(NSDate.distantFuture) until @parsed
end
def parserDidStartDocument(parser)
puts "starting parsing.."
end
# Delegate being called when an element starts being processed
def parser(parser, didStartElement:element, namespaceURI:uri, qualifiedName:name, attributes:attrs)
if element == 'item'
@current_item = RSSItem.new
elsif element == 'enclosure'
@current_item.enclosure = attrs
end
@current_element = element
end
# as the parser finds characters, this method is being called
def parser(parser, foundCharacters:string)
if @current_item && @current_item.respond_to?(@current_element)
el = @current_item.send(@current_element)
el << string
end
end
# method called when an element is done being parsed
def parser(parser, didEndElement:element, namespaceURI:uri, qualifiedName:name)
if element == 'item'
@items << @current_item
end
end
def parserDidEndDocument(parser)
@parsed = true
puts "done parsing"
if @block
@items.each{|item| @block.call(item)}
end
end
end
lemonde = RSSParser.new("http://www.lemonde.fr/rss/une.xml")
lemonde.block_while_parsing do |item|
puts item.link
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment