11 Jul

Modifying Action Text markup - Rails Tricks Issue 14


Hi there,


I am working on a newsletter tool(Pombo) and this week, I want to share how I solved a problem I came across last week while working on it.


The problem: the newsletter tool needs to support importing past issues from other tools. These imported issues might contain references to images hosted at the other provider, and during the import, I need to move those images into Pombo because once the account on the old service is deleted, the images won’t be accessible anymore.


In Pombo, I use Action Text to store the body of a newsletter issue, and I use Active Storage for the images. My initial plan was to parse the HTML output of the Action Text field with Nokogiri, extract the image tags, create an Active Storage blob from them, and replace the image tag’s src in the markup to the blob’s URL.
Then I decided to look at Action Text’s source code to see how it works under the hood, and it turned out it will be way easier to do what I need than I expected.
An Action Text field has a “body” attribute, which is an instance of ActionText::Content which has a fragment method, which returns an instance of ActionText::Fragment and that’s a wrapper around the Nokogiri parsed markup.
Now putting this all together, to find all image tags on a content attribute backed by Action Text, we can just do the following:

9fdfbd14-0fd2-45d6-830b-3958d416bd5c.png 13.9 KB The next part is to download the image and create an ActiveStorage::Blob: 85ee56bd-e94a-4bcd-a3b5-8a96be1f0391.png 104 KB Next thing to figure out is how to replace the old image with the new one.
Digging a bit more into Action Text, I figured out I need to create an ActionText::Attachment from the blob and replace the nokogiri node with that: e622f146-580d-402c-af29-893dc75c21fd.png 53.6 KB And finally, we need to save the changes on the content. Here is the full snippet: fc440b3a-40ed-4930-a1df-364f698d2c8a.png 150 KB Based on what I learned from figuring out this solution, it will be pretty easy to add an outgoing link validator to make sure a newsletter doesn’t contain broken links.

I hope you enjoyed this, until next time!