Class: Hackernews::Client

Inherits:
Object
  • Object
show all
Includes:
HTTParty
Defined in:
lib/hackernews/client.rb

Constant Summary collapse

FEEDS =
{
  "top" => "topstories",
  "new" => "newstories",
  "best" => "beststories",
  "ask" => "askstories",
  "show" => "showstories",
  "jobs" => "jobstories"
}.freeze
DEFAULT_LIMIT =
500
DEFAULT_PER_PAGE =
30
DEFAULT_CONCURRENCY =
8

Instance Method Summary collapse

Constructor Details

#initialize(per_page: DEFAULT_PER_PAGE, limit: DEFAULT_LIMIT, concurrency: DEFAULT_CONCURRENCY) ⇒ Client

Returns a new instance of Client.



25
26
27
28
29
# File 'lib/hackernews/client.rb', line 25

def initialize(per_page: DEFAULT_PER_PAGE, limit: DEFAULT_LIMIT, concurrency: DEFAULT_CONCURRENCY)
  @per_page = per_page
  @limit = limit
  @concurrency = concurrency
end

Instance Method Details

#item(id) ⇒ Object



49
50
51
# File 'lib/hackernews/client.rb', line 49

def item(id)
  Story.from_hash(fetch_json("/item/#{id}.json"))
end

#stories(feed:, page: 0) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/hackernews/client.rb', line 31

def stories(feed:, page: 0)
  feed = feed.to_s
  ids = story_ids(feed).first(limit)
  page_ids = ids.slice(page.to_i * per_page, per_page) || []

  {
    feed: feed,
    page: page.to_i,
    ids: ids,
    stories: stories_for_ids(page_ids)
  }
end

#story_ids(feed) ⇒ Object



44
45
46
47
# File 'lib/hackernews/client.rb', line 44

def story_ids(feed)
  endpoint = FEEDS.fetch(feed.to_s) { FEEDS.fetch("top") }
  fetch_json("/#{endpoint}.json")
end