Skip to content

Commit

Permalink
pre-render blog::post content
Browse files Browse the repository at this point in the history
  • Loading branch information
fwolfst committed Oct 9, 2020
1 parent 9d5796c commit 65c7b52
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 5 deletions.
9 changes: 9 additions & 0 deletions app/models/blog/post.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ class Blog::Post < ApplicationRecord

scope :published, -> { active.where.not(published_at: nil) }

before_save :render_markdown,
if: -> {content_changed? || content.present? != content_rendered.present?}

# Not using a scope here because of 'first'
def self.last_within days: 7.days
Expand All @@ -30,4 +32,11 @@ def next
Blog::Post.published.where("created_at > ?", created_at)
.order(created_at: :asc).where.not(id: id).first
end

def render_markdown
renderer = Redcarpet::Render::HTML.new(with_toc_data: true)
assign_attributes({
content_rendered: Redcarpet::Markdown.new(renderer).render(content)
})
end
end
5 changes: 1 addition & 4 deletions app/views/blog/posts/show.html.haml
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,7 @@
= l(@post.published_at, format: :worded)

.container.content
-# TODO do not render markdown in the view
-#= @post.content
- renderer = Redcarpet::Render::HTML.new(with_toc_data: true)
!= Redcarpet::Markdown.new(renderer).render(@post.content)
!= @post.content_rendered

%hr

Expand Down
10 changes: 10 additions & 0 deletions db/migrate/20201009052202_add_content_rendered_to_blog_post.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# SPDX-FileCopyrightText: 2020 Felix Wolfsteller
#
# SPDX-License-Identifier: AGPL-3.0-or-later

class AddContentRenderedToBlogPost < ActiveRecord::Migration[6.0]
def change
add_column :blog_posts, :content_rendered, :text
Blog::Post.find_each {|p| p.save!}
end
end
3 changes: 2 additions & 1 deletion db/schema.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
#
# It's strongly recommended that you check this file into your version control system.

ActiveRecord::Schema.define(version: 2020_10_07_174709) do
ActiveRecord::Schema.define(version: 2020_10_09_052202) do

create_table "active_storage_attachments", force: :cascade do |t|
t.string "name", null: false
Expand Down Expand Up @@ -53,6 +53,7 @@
t.datetime "updated_at", precision: 6, null: false
t.text "summary"
t.datetime "published_at"
t.text "content_rendered"
t.index ["slug"], name: "index_blog_posts_on_slug", unique: true
end

Expand Down

0 comments on commit 65c7b52

Please sign in to comment.