Skip to content
9 changes: 9 additions & 0 deletions app/models/concerns/post_normalizations.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
module PostNormalizations
extend ActiveSupport::Concern

class_methods do
def normalize_newlines(text)
text.encode(text.encoding, universal_newline: true).strip
end
end
end
1 change: 1 addition & 0 deletions app/models/post.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
class Post < ApplicationRecord
include CommunityRelated
include Lockable
include PostNormalizations
include PostValidations
include SoftDeletable
include Timestamped
Expand Down
7 changes: 2 additions & 5 deletions app/models/post_history.rb
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
class PostHistory < ApplicationRecord
include PostNormalizations
include PostRelated
include EditsValidations

Expand All @@ -11,11 +12,7 @@ class PostHistory < ApplicationRecord
scope :of_type, ->(name) { joins(:post_history_type).where(post_history_types: { name: name }) }
scope :on_undeleted, -> { joins(:post).where(posts: { deleted: false }) }

normalize_newlines = lambda { |text|
text.encode(text.encoding, universal_newline: true)
}
normalizes :before_state, with: normalize_newlines
normalizes :after_state, with: normalize_newlines
normalizes :before_state, :after_state, with: ->(text) { normalize_newlines(text) }

def before_tags
tags.where(post_history_tags: { relationship: 'before' })
Expand Down
4 changes: 3 additions & 1 deletion app/views/post_history/_diff.html.erb
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
<div class="diff">
<% if before.present? && after.present? %>
<% if before.is_a?(String) && after.is_a?(String) %>
<% diff = Diffy::SplitDiff.new(before, after, format: :html, ignore_crlf: true) %>
<% before = Post.normalize_newlines(before) %>
<% after = Post.normalize_newlines(after) %>
<% diff = Diffy::SplitDiff.new(before, after, format: :html) %>
<div class="diff-section">
<div class="diff-old is-changed raw-markdown">
<%= raw(diff.left) %>
Expand Down
2 changes: 1 addition & 1 deletion test/controllers/posts/update_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ class PostsControllerTest < ActionController::TestCase
post = posts(:question_three)
before_history = PostHistory.where(post: post).count
bm = post.body_markdown
body_markdown_with_crlf = bm.encode(bm.encoding, normalize_newlines: true).split("\n").join("\r\n")
body_markdown_with_crlf = bm.encode(bm.encoding, universal_newline: true).split("\n").join("\r\n")
patch :update, params: { id: post.id,
post: { title: post.title,
body_markdown: body_markdown_with_crlf,
Expand Down
Loading