Adding Alt Text To Images
Adding alt text to “previewable attachments” is quite a challenge. Rhino Editor comes with support built in, but it requires patching ActionText, so it is not part of the default experience.
To start, lets configure ActionText to allow us to add the "alt"
attribute to attachments.
I have tried using other attribute names such as “alt-text”, “altText”, and “alt_text” but ActionText / ActiveStorage seem to sanitize it away.
To configure ActionText, we can create a file at config/initializers/actiontext_patch.rb
and add the following content:
# config/initializers/actiontext_patch.rb
attributes = ActionText::TrixAttachment::ATTRIBUTES + ["alt"]
ActionText::TrixAttachment.const_set("ATTRIBUTES", attributes)
attributes = ActionText::Attachment::ATTRIBUTES + ["alt"]
ActionText::Attachment.const_set("ATTRIBUTES", attributes)
If this looks funky to you, thats because it is. I filed an issue with Rails about proper mattr_accessor
support like other Rails modules to make this API nicer to work with.
https://github.com/rails/rails/discussions/54179
Moving on, now that ActionText can accept the “alt” attribute, we have to configure Rhino Editor to enable the alt text editor.
Enabling alt text editor
To enable the alt text editor, we can do the following:
Alt text editor example
Add an attachment below to test out the attachment editor.
Add the alt attribute to your attachments
The final step to making our alt text work is we need to modify app/views/active_storage/blobs/_blob.html.erb
By default this file should look something like this:
What we need to do is modify a couple of lines to add the alt text:
And thats it! You should be all set up with alt text now!