Module: HackerNews::StoryList

Defined in:
lib/hnruby/storylist.rb

Overview

Represents an opaque list of all stories on Hacker News.

Each story is cached the first time it’s accessed (or the first time the page it’s on is accessed), so they may become out of date quickly. If you need to refresh constantly, call StoryList.update before retrieving any stories.

story = HackerNews::StoryList[1]
sleep 300
story == HackerNews::StoryList[1]	#=> true
HackerNews::StoryList.update
story == HackerNews::StoryList[1]	#=> false

Constant Summary collapse

@@items =
{}

Class Method Summary collapse

Class Method Details

.[](i) ⇒ Object

If index is a number, returns a NewsItem representing the story currently at index.

If index is a range, return all stories with ranks in index.

s = HackerNews::StoryList[1]       \
#=> "DMCA takedown on GPL-copyrighted code" <article: 6623329>

s = HackerNews::StoryList[2..3]    \
#=> ["C--" <article: 6621679>, "Profitless Prosperity" <article: 6622394>]

:arg: index



50
51
52
53
54
55
56
57
58
# File 'lib/hnruby/storylist.rb', line 50

def self.[](i)
	if i.is_a? Numeric
		self.at i.to_i
	elsif i.is_a? Enumerable
		self.stories i
	else
		raise TypeError
	end
end

.at(i) ⇒ Object

Returns a NewsItem representing the story currently at index. Equivalent to HackerNews::StoryList[index]. :arg: index



63
64
65
66
67
# File 'lib/hnruby/storylist.rb', line 63

def self.at(i)
	update_page ((i - 1) / 30) + 1 unless @@items[i]

	@@items[i]
end

.front_pageObject

Returns an array of the stories currently on the front page.



75
76
77
# File 'lib/hnruby/storylist.rb', line 75

def self.front_page
	(1..30).map{ |i| at i }
end

.page(index) ⇒ Object

Returns an array of all the stories on the indexth page.



70
71
72
# File 'lib/hnruby/storylist.rb', line 70

def self.page(index)
	((((index - 1) * 30) + 1)..(index * 30)).map{ |i| at i }
end

.stories(range) ⇒ Object

Returns all the stories with ranks in range. Equivalent to HackerNews::StoryList[range].



81
82
83
# File 'lib/hnruby/storylist.rb', line 81

def self.stories(range)
	range.map{ |i| at i }
end

.updateObject

Clear story cache— any actual NewsItem objects will still need to be updated, though.



34
35
36
# File 'lib/hnruby/storylist.rb', line 34

def self.update
	@@items = {}
end