Sanitizing HTML in Rails with strip_tags

In some API responses, it’s necessary to return plain text even when the original method outputs HTML. This can be challenging when the source method can’t be modified and the response format must follow strict requirements.

The Situation

Consider a serializer method that returns a spots_left field like this:

1
2
3
4
5
6
7
8
9
class Api::V40::SlotSerializer

  def cta_availability
    {
      status: object.status,
      spots_left: object.available_vacancies_tag
    }
  end
end

But object.available_vacancies_tag returns HTML like this:

1
<h5 class="text_center">Limited spots left!</h5>

But the API response is expected to look like this:

1
"spots_left": "Limited spots left!"

Again, without changing the original available_vacancies_tag method.

The Solution

To remove HTML tags from a field in a Rails serializer, use the strip_tags method, which comes from the ActionView::Helpers::SanitizeHelper module.

To use it, simply include the helper at the top of the class: include ActionView::Helpers::SanitizeHelper. This allows strip_tags to be applied directly to the spots_left key, ensuring the HTML is stripped without modifying the original method.

1
2
3
4
5
6
7
8
9
10
class Api::V40::SlotSerializer
  include ActionView::Helpers::SanitizeHelper

  def cta_availability
    {
      status: object.status,
      spots_left: strip_tags(object.available_vacancies_tag.to_s)
    }
  end
end

This approach helps to deliver the expected API response format without breaking the separation of concerns.