10

First let me say that I love what Rails 6 has to offer in ActionText. Unfortunately when I declare it for an attribute in something like a post model:

class Post < ApplicationRecord
  has_rich_text :body
end

I can't access the body's text anymore. It becomes an ActionText instance. I completely understand this is how this functionality works but there are times I need to pass the plain text of the body to other external methods. In my case I'm using the body in my meta-description tags with a gem called meta-tags. Doing so results in this error:

Expected a string or an object that implements #to_str

This is because what was before a plain text column becomes an AT instance:

=> #<ActionText::RichText id: 39, name: "body", body: #<ActionText::Content "<div class=\"trix-conte...">, record_type: "Post", record_id: 161, created_at: "2019-08-17 17:34:27", updated_at: "2019-08-17 17:34:27"> 

Seeing that it had getter methods attached with it I tried to do something like @post.body.body but this is actually

=> #<ActionText::Content "<div class=\"trix-conte...">

Also note that I've tried to create a method inside the post model but once has_rich_text is declared I no longer have original access to my body's text.

I'm not exactly sure how to:

  • Extract my original content from the body attribute Convert it to plain text without html
Carl Edwards
  • 13,826
  • 11
  • 57
  • 119

3 Answers3

24

So apparently ActionText instances have a method for retrieving plain text values with to_plain_text. All together it looks like this:

@post.body => <div>This is my markup</div>
@post.body.to_plain_text => This is my markup
Carl Edwards
  • 13,826
  • 11
  • 57
  • 119
1

on top of to_plain_text, we can call squish to remove the new line '\n'

lhjd
  • 13
  • 1
  • 6
1

Yes the answer by Carl is correct

@post.body.to_plain_text #=> This is my markup without image

However if you have any attachments (eg blob image) inside your action text then they will appear like

@post.body.to_plain_text #=> This is my markup with image[PXL_20210808_152511813.jpeg] 

This is due to this code which is called on every attachment when #to_plain_text it called

If you are in a case where you don't want to Display text for blob attachments you need to overwrite ActiveStorage::Blob#attachable_plain_text_representation

One way to do this:

# config/initializers/active_storage_overrides.rb

module ActiveStorageBlobOverrides
  def attachable_plain_text_representation(caption = nil)
    ""
  end
end

Rails.configuration.to_prepare do
  ActiveStorage::Blob.send :prepend, ::ActiveStorageBlobOverrides
end

How are you will end up with:

@post.body.to_plain_text #=> This is my markup with image 

I hope this will save you a couple of hours of debugging

equivalent8
  • 13,754
  • 8
  • 81
  • 109