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.

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>


99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/hnruby/comment.rb', line 99

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

  html = Nokogiri::HTML(open(url), nil, "UTF-8")
  @title = html.title.chomp " | Hacker News"
  @url = url

  html = (html / "tr")[8..-3]
  @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

#titleObject (readonly)

Returns this comment page’s title.



88
89
90
# File 'lib/hnruby/comment.rb', line 88

def title
  @title
end

#urlObject (readonly)

Returns the URL for this comment page on Hacker News.



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

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



118
119
120
121
# File 'lib/hnruby/comment.rb', line 118

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

#inspectObject

:nodoc:



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

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

#to_aObject

Returns array containing every Comment object within the page.



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

def to_a
  @comments
end

#to_sObject

:nodoc:



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

def to_s
  inspect
end