Save 36% for Black Friday! Learn more

Blog / How to render ActionText Attachments in Plain Text

How to render ActionText Attachments in Plain Text

Chris Oliver

November 2, 2021

ActionText supports custom attachments using Signed Global IDs. We can use this to embed any database record in Rails such as @mentions for users.

For HTML, Rails will use the to_partial_path to render the HTML template for the attachment. For a user, this would be app/views/users/_user.html.erb.

With Plain Text output, Rails will default to the caption specified on the attachable. Typically, this is nil because we don't need a caption for an @mention.

By defining the attachable_plain_text_representation method, we can specify the default value for the plain text ActionText output.

class User
  include ActionText::Attachable

  # When ActionText rendering mentions in plain text
  def attachable_plain_text_representation(caption = nil)
    caption || name
  end

And that's it! Simply render your ActionText content as plain text and it will use this method for rendering.

P.S. You might enjoy following me on Twitter.


Comments
Loading...

Want to stay up-to-date with Ruby on Rails?

Join 54,329+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2021 GoRails, LLC. All rights reserved.