Class: RedditPostToMarkdown::PostRenderer
- Inherits:
-
Object
- Object
- RedditPostToMarkdown::PostRenderer
- Defined in:
- lib/reddit_post_to_markdown/post_renderer.rb
Overview
Converts Reddit post data and its comments into a Markdown string.
The output format matches the reddit-markdown tool: post header, title, selftext, reply count, and a depth-indented comment tree.
Constant Summary collapse
- DEFAULT_FILTERED_MESSAGE =
Replacement text used when a comment matches a filter and no custom
:messageis provided in the filters hash. "REMOVED DUE TO CUSTOM FILTER(S)"
Class Method Summary collapse
-
.render(post_data, replies_data, filters: {}) ⇒ String
Renders a Reddit post and its comments as a Markdown string.
Instance Method Summary collapse
-
#initialize(post_data, replies_data, filters = {}) ⇒ PostRenderer
constructor
A new instance of PostRenderer.
-
#render ⇒ String
Renders the post and all its comments as a single Markdown string.
Constructor Details
#initialize(post_data, replies_data, filters = {}) ⇒ PostRenderer
Returns a new instance of PostRenderer.
34 35 36 37 38 |
# File 'lib/reddit_post_to_markdown/post_renderer.rb', line 34 def initialize(post_data, replies_data, filters = {}) @post_data = post_data @replies_data = replies_data @filters = filters || {} end |
Class Method Details
.render(post_data, replies_data, filters: {}) ⇒ String
Renders a Reddit post and its comments as a Markdown string.
This is the primary entry point for the class. It instantiates a renderer and calls #render.
27 28 29 |
# File 'lib/reddit_post_to_markdown/post_renderer.rb', line 27 def self.render(post_data, replies_data, filters: {}) new(post_data, replies_data, filters).render end |
Instance Method Details
#render ⇒ String
Renders the post and all its comments as a single Markdown string.
Sections in order:
-
Post header (subreddit, author, upvotes, timestamp)
-
Post title as an H2
-
Link back to the original post
-
Lock notice (if the thread is locked)
-
Post body / selftext as a block-quote (if present)
-
Total reply count
-
Horizontal rule
-
Comment tree, depth-indented with tab characters
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 |
# File 'lib/reddit_post_to_markdown/post_renderer.rb', line 53 def render lines = [] # Post header lines << "#{header_line}" lines << "## #{post_title}" lines << "Original post: [#{post_url}](#{post_url})" lines << if post_locked? # Selftext if post_selftext && !post_selftext.strip.empty? decoded = decode_selftext(post_selftext) lines << "> #{decoded.gsub("\n", "\n> ")}" end image_urls = post_image_urls() if image_urls.size > 0 lines << "### Images" image_urls.each do |url| lines << "" end lines << "" end # Reply count + separator total = count_all_replies lines << "💬 ~ #{total} replies" lines << "---\n" # Top-level comments @replies_data.each do |reply_obj| render_top_level_reply(reply_obj, lines) end lines.join("\n") end |