Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Rubocop do not allow html_safe or raw() Rails

here is my code who do not pass Rubocop because :

Rails/OutputSafety: Tagging a string as html safe may be a security risk.

def number_with_html_delimiter(num)
   number_with_delimiter(num)
      .gsub!(' ', content_tag(:span, "", class: "numbers-delimiter")).html_safe
end

I need to put a custom span with some css to put the spaces in HTML and when I remove html_safe it does not work.

Please help, thanks in advance

like image 645
Kara Avatar asked Oct 11 '25 13:10

Kara


2 Answers

html_safe and raw() are not safe for security purpose. You can disable rubocop for html_safe(or raw) by using # rubocop:disable Rails/OutputSafety and # rubocop:enable Rails/OutputSafety before and after code where you have used html_safe(or raw) method.

# rubocop:disable Rails/OutputSafety
def number_with_html_delimiter(num)
   number_with_delimiter(num)
      .gsub!(' ', content_tag(:span, "", class: "numbers-delimiter")).html_safe
end
#rubocop:enable Rails/OutputSafety
like image 192
Niraj Kaushal Avatar answered Oct 14 '25 11:10

Niraj Kaushal


It is recommended to use sanitize for common tags and attributes by Rails docs.

In your helper:

# Use `!` to indicate that `sanitize` should be used
def number_with_html_delimiter!(num)
   number_with_delimiter(num)
      .gsub(' ', content_tag(:span, "", class: "numbers-delimiter")).html_safe
end

In your view:

<%= sanitize number_with_html_delimiter!(1000) %>
like image 43
Aidi Stan Avatar answered Oct 14 '25 12:10

Aidi Stan