Class: HackerNews::CommentPage

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/hnruby/comment.rb

Overview

Represents the list of comments pertaining to a particluar HN story.


TODO: Support self-post content, polls, etc.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(url) ⇒ CommentPage

Returns a new CommentPage corresponding to url.

cpage = HackerNews::CommentPage.new\
"https://news.ycombinator.com/item?id=6621679"  #=> "C--" <12 Comments>

Alternately, if passed an integer, returns the CommentPage corresponding to the story whose ID is url.

cpage = HackerNews::CommentPage.new 6621679 #=> "C--" <12 Comments>


103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/hnruby/comment.rb', line 103

def initialize(url)
  @url = url.is_a?(Numeric) ? "#{HN_URL}item?id=#{url.to_i}" : url

  html = Nokogiri::HTML(open(@url), nil, "UTF-8")
  @title = html.title.chomp " | Hacker News"
  @story_url = ((html / "tr")[4] / "td")[1].at("a").attribute("href").value

  html = (html / "tr")[(@story_url.start_with?("item?id=") ? 10 : 8)..-3].
      drop_while { |i| i.children.length != 1 } # Fixes polls and such
  @comments = []
  lineage = []
  (0...html.length).select{ |i| i.even? }.each do |i|
    com = Comment.new html[i]
    com.parent = com.depth > 0 ? lineage[com.depth - 1] : nil
    lineage[com.depth] = com
    @comments << com
  end
end

Instance Attribute Details

#story_urlObject (readonly)

Returns the URL for the story corresponding to this comment page.



94
95
96
# File 'lib/hnruby/comment.rb', line 94

def story_url
  @story_url
end

#titleObject (readonly)

Returns this comment page’s title.



90
91
92
# File 'lib/hnruby/comment.rb', line 90

def title
  @title
end

#urlObject (readonly)

Returns the URL for this comment page on Hacker News.



92
93
94
# File 'lib/hnruby/comment.rb', line 92

def url
  @url
end

Instance Method Details

#[](index) ⇒ Object

Returns the Comment object at index.



129
130
131
# File 'lib/hnruby/comment.rb', line 129

def [](index)
  @comments[index]
end

#at(index) ⇒ Object

Returns the Comment object at index. Equivalent to self[index].



135
136
137
# File 'lib/hnruby/comment.rb', line 135

def at(index)
  @comments[index]
end

#eachObject

Passes all comments in self as a block



123
124
125
126
# File 'lib/hnruby/comment.rb', line 123

def each
  @comments.each { |i| yield i }
  self
end

#inspectObject

:nodoc:



145
146
147
# File 'lib/hnruby/comment.rb', line 145

def inspect
  "\"#{@title}\" <#{@comments.length} comments>"
end

#lengthObject

Returns the number of comments in self.



140
141
142
# File 'lib/hnruby/comment.rb', line 140

def length
  @comments.length
end

#to_sObject

:nodoc:



150
151
152
# File 'lib/hnruby/comment.rb', line 150

def to_s
  inspect
end