Rails 6 removes Action View helper image_alt


Rails 5.2 deprecated the Action View helper image_alt(src).

The method takes the src argument, which can be an image file path. It removes the basename and the digest of the image file path, and returns a titleized string after replacing hyphens and underscores with spaces.

Let’s see an example:

2.6.5 :002 > image_alt('images/pencil-icon.png')
 => "Pencil icon"
2.6.5 :003 > image_alt('images/admin_user_icon.png')
 => "Admin user icon"
 

Usage in image_tag

Before deprecation, image_alt was used to autogenerate alt text from the src attribute of an image_tag.

Example:

Adding the following in a view:

<%= image_tag 'brand-logo.png' %>

Would render:

<image src='/images/brand-logo.png' alt='Brand logo'>

Problems with default alt text

In the example above, the alt text “Brand logo” will be read by screen readers.

More often than not, this automatically inferred text is not a useful description and adds unnecessary content.

Setting a meaningless alt text messes with the screen reader’s default behavior for blank alt text. That may be frustrating for assistive technology users.

This also results in linting tools giving false negatives.

It also makes improving application accessibility a tough job.

Rails 5.2 onwards

After deprecation, we had to explicitly set the alt text while using an image_tag.
And also had the option to just not provide an alt text. The generated image tag would have no alt text in that case.

Example:

<%= image_tag 'brand-logo.png', alt: 'Company name' %>
<%= image_tag 'user-placeholder.png' %>

Would render:

<image src='/images/brand-logo.png' alt='Company name'>  
<image src='/images/brand-logo.png'>

Rails 6.0

In Rails 6.0, this method has been removed. This was done as a part of removing all code which was deprecated in Rails 5.2.