Watson1978
5/22/2012 - 2:49 PM

rss_parser.rb

#!/usr/local/bin/macruby
framework "Cocoa"
require 'pp'

class RSS
  def parse(url,
            delegate: delegate,
            selector: callback)
    @delegate = delegate
    @callback = callback

    xml = NSXMLParser.alloc.initWithContentsOfURL(url)
    xml.delegate = self
    xml.parse
  end

  def parserDidStartDocument(parser)
    @item = {}
  end

  def parserDidEndDocument(parser)
    if @delegate.respond_to?("parserDidEndDocument")
      @delegate.send("parserDidEndDocument")
    end
  end

  def parser(parser,
             didStartElement: elementName,
             namespaceURI: namespaceURI,
             qualifiedName: qualifiedName,
             attributes: attributeDict)
    @string = ""
  end

  def parser(parser,
             didEndElement: elementName,
             namespaceURI: namespaceURI,
             qualifiedName: qName)
    @item[elementName] = @string
    if elementName == "item"
      @delegate.send(@callback, @item)
      @item = {}
    end
  end

  def parser(parser,
             foundCharacters: string)
    @string << string.strip
  end
end

class NSString
  def to_url
    NSURL.URLWithString(self)
  end
end



if __FILE__ == $0
  class Sample
    def initialize
      RSS.new.parse("http://www.apple.com/jp/main/rss/hotnews/hotnews.rss".to_url,
                    delegate: self,
                    selector: "getRssItem:")
    end

    def getRssItem(obj)
      pp obj
    end

    def parserDidEndDocument
      exit
    end
  end

  app = NSApplication.sharedApplication
  app.delegate = Sample.new
  app.run
end