Class: HackerNews
- Inherits:
-
Object
- Object
- HackerNews
- Defined in:
- lib/hackernews.rb
Constant Summary collapse
- VERSION =
'0.1.0'
- BASE_URL =
'http://news.ycombinator.com'
- USER_URL =
'http://news.ycombinator.com/user?id=%s'
Class Method Summary collapse
-
.version ⇒ Object
Returns the version string for the library.
Instance Method Summary collapse
-
#average_karma ⇒ Object
Retrieves the average karma per post for the logged in user.
-
#initialize(username, password) ⇒ HackerNews
constructor
Creates a new HackerNews object.
-
#karma(username = nil) ⇒ Object
Retrieves the karma for the logged in user, or for the specified username (if given).
-
#user_page(username = nil) ⇒ Object
Retrieves the user page html for the specified username (or the current logged in user if none is specified).
Constructor Details
#initialize(username, password) ⇒ HackerNews
Creates a new HackerNews object. Specify your username and password.
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
# File 'lib/hackernews.rb', line 19 def initialize(username, password) login_url = open(BASE_URL).read.match(/href="([^"]+)">login<\/a>/)[1] form_html = open(BASE_URL + login_url).read submit_url = URI.parse(BASE_URL) response = Net::HTTP.new(submit_url.host, submit_url.port).start do |http| req = Net::HTTP::Post.new('/y') req.set_form_data( 'fnid' => form_html.match(/<input type=hidden name="fnid" value="([^"]+)"/)[1], 'u' => username, 'p' => password ) http.request(req) end @cookie = response.header['set-cookie'] @username = username @password = password end |
Class Method Details
.version ⇒ Object
Returns the version string for the library.
10 11 12 |
# File 'lib/hackernews.rb', line 10 def self.version VERSION end |
Instance Method Details
#average_karma ⇒ Object
Retrieves the average karma per post for the logged in user.
43 44 45 |
# File 'lib/hackernews.rb', line 43 def average_karma user_page.match(/<td valign=top>avg:<\/td><td>([\d\.]+)<\/td>/)[1] end |
#karma(username = nil) ⇒ Object
Retrieves the karma for the logged in user, or for the specified username (if given).
38 39 40 |
# File 'lib/hackernews.rb', line 38 def karma(username=nil) user_page(username).match(/<td valign=top>karma\:<\/td><td>(\d+)<\/td>/)[1] end |
#user_page(username = nil) ⇒ Object
Retrieves the user page html for the specified username (or the current logged in user if none is specified).
48 49 50 51 52 53 54 55 56 57 58 59 |
# File 'lib/hackernews.rb', line 48 def user_page(username=nil) username ||= @username @user_pages ||= {} @user_pages[username] ||= begin url = URI.parse(USER_URL % username) response = Net::HTTP.start(url.host, url.port) do |http| header = {'Cookie' => @cookie} http.get(url.path + '?' + url.query, header) end response.body end end |