Class: FeedParser::Feed

Inherits:
Object
  • Object
show all
Defined in:
lib/feed_parser/feed.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(feed_xml) ⇒ Feed

Returns a new instance of Feed.



5
6
7
8
9
10
11
# File 'lib/feed_parser/feed.rb', line 5

def initialize(feed_xml)
  @feed = Nokogiri::XML(feed_xml)
  @feed.remove_namespaces!
  @type = ((@feed.xpath('/rss')[0] && :rss) || (@feed.xpath('/feed')[0] && :atom))
  raise FeedParser::UnknownFeedType.new("Feed is not an RSS feed or an ATOM feed") unless @type
  self
end

Instance Attribute Details

#typeObject (readonly)

Returns the value of attribute type.



3
4
5
# File 'lib/feed_parser/feed.rb', line 3

def type
  @type
end

Instance Method Details

#as_jsonObject



38
39
40
41
42
43
44
# File 'lib/feed_parser/feed.rb', line 38

def as_json
  {
    :title => title,
    :url => url,
    :items => items.map(&:as_json)
  }
end

#itemsObject



30
31
32
33
34
35
36
# File 'lib/feed_parser/feed.rb', line 30

def items
  klass = (@type == :rss && RssItem || AtomItem)

  @items ||= @feed.xpath(Dsl[@type][:item]).map do |item|
    klass.new(item)
  end
end

#titleObject



13
14
15
# File 'lib/feed_parser/feed.rb', line 13

def title
  @title = @feed.xpath(Dsl[@type][:title]).text
end

#urlObject



17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/feed_parser/feed.rb', line 17

def url
  _url = case @type
    when :rss
      @feed.xpath(Dsl[@type][:url])
    when :atom
      @feed.xpath(Dsl[@type][:url]).first && @feed.xpath(Dsl[@type][:url]).attribute("href") ||
      @feed.xpath(Dsl[@type][:alternate_url]).first && @feed.xpath(Dsl[@type][:alternate_url]).attribute("href")
    else
      nil
  end
  @url = _url && _url.text || ""
end