Class: RedditPostToMarkdown::RedditClient
- Inherits:
-
Object
- Object
- RedditPostToMarkdown::RedditClient
- Includes:
- HTTParty
- Defined in:
- lib/reddit_post_to_markdown/reddit_client.rb
Overview
Fetches Reddit post JSON via the public Reddit API.
Requests are made without authentication using Reddit’s .json endpoint, which is available for any public post.
Constant Summary collapse
- USER_AGENT =
"RedditPostToMarkdown/#{VERSION} (Safe Download Bot)"
Instance Method Summary collapse
-
#fetch_post(url) ⇒ Array
Downloads the JSON data for a Reddit post URL.
Instance Method Details
#fetch_post(url) ⇒ Array
Downloads the JSON data for a Reddit post URL.
Appends .json to url (unless already present) and issues a GET request. Reddit returns a two-element array: the first element contains the post data and the second contains the top-level comments.
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
# File 'lib/reddit_post_to_markdown/reddit_client.rb', line 26 def fetch_post(url) json_url = url.end_with?(".json") ? url : "#{url}.json" response = self.class.get(json_url, headers: { "User-Agent" => USER_AGENT }) raise FetchError, "HTTP #{response.code} fetching #{url}" unless response.success? data = response.parsed_response unless data.is_a?(Array) && data.length >= 2 raise InvalidResponseError, "Expected a 2-element JSON array from #{url}" end data end |