code snippets

Add target and other attributes to elements in Rails

November 25, 2022 10:00

The use-case

Today we changed the design of our blog a bit and wanted to add photo credits to each post. Moving fast is important to us, so we added a migration r g migration add_photo_credits_to_posts photo_credits:text, added the field to the Avo resource field :photo_credits, as: :text and the proper tags to the erb file.

The flow is to go on Unsplash or our photo library of choice, download the image, upload in Avo, copy the credits, paste them into Avo and save.

The problem

It sounds simple, but it seems that Unsplash copies the credits with links without the `target="_blank" attribute. So, let's fix that.

The fix

Add a before_save hook to our model that changes all the links in that attribute to add the target and rel attributes.

class Post < ApplicationRecord
  before_save -> {
    # Load up and parse the current attribute
    doc = Nokogiri::HTML.fragment(photo_credit)
    # Iterate through all links
    doc.css('a').each do |link|
      # Add the attributes
      link['target'] = '_blank'
      link['rel'] = 'noopener'
    # Assign back to the model
    self.photo_credit = doc.to_s

Done 🙌 Now, every time we save the post, we are sure that the links have the proper attributes assigned.