Skip to content

Commit

Permalink
Empty embeds when RichText is set to an empty content
Browse files Browse the repository at this point in the history
Fix rails#51269

Action Text supports saving a RichText model with empty content. Passing _almost_ empty content (such as a space) flushes the embeds, but passing truly empty content does not. This defies expectations.

This change ensures that the embeds are flushed when empty content is passed.
  • Loading branch information
JoeDupuis committed Oct 15, 2024
1 parent aeb0828 commit 4a4f7a7
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 1 deletion.
4 changes: 4 additions & 0 deletions actiontext/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
* Clear embeds when emptying an `ActionText::RichText`.

*Joé Dupuis*

## Rails 8.0.0.beta1 (September 26, 2024) ##

* Dispatch direct-upload events on attachment uploads
Expand Down
2 changes: 1 addition & 1 deletion actiontext/app/models/action_text/rich_text.rb
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ class RichText < Record
has_many_attached :embeds

before_save do
self.embeds = body.attachables.grep(ActiveStorage::Blob).uniq if body.present?
self.embeds = body.blank? ? [] : body.attachables.grep(ActiveStorage::Blob).uniq
end

# Returns a plain-text version of the markup contained by the `body` attribute,
Expand Down
22 changes: 22 additions & 0 deletions actiontext/test/unit/model_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,28 @@ class ActionText::ModelTest < ActiveSupport::TestCase
end
end

test "saving empty content empties the embeds" do
blob = create_file_blob(filename: "racecar.jpg", content_type: "image/jpeg")
message = Message.create!(subject: "Greetings", content: ActionText::Content.new("Hello world").append_attachables(blob))
assert message.content.embeds.sole

message.content = ""
message.save

assert_empty message.content.embeds
end

test "saving nil content empties the embeds" do
blob = create_file_blob(filename: "racecar.jpg", content_type: "image/jpeg")
message = Message.create!(subject: "Greetings", content: ActionText::Content.new("Hello world").append_attachables(blob))
assert message.content.embeds.sole

message.content = nil
message.save

assert_empty message.content.embeds
end

test "saving content" do
message = Message.create!(subject: "Greetings", content: "<h1>Hello world</h1>")
assert_equal "Hello world", message.content.to_plain_text
Expand Down

0 comments on commit 4a4f7a7

Please sign in to comment.