How do I define a method in Ruby to have the same function of escapeHTML?

StackOverflow https://stackoverflow.com/questions/22493430

  •  17-06-2023
  •  | 
  •  

Вопрос

I want code that uses a method named "h" to have the same output this code in ERB does:

<code>
  <%= CGI::escapeHTML(the_string) %>
</code>

Output of above code:

<!doctype html> <head><meta charset="utf-8"><title>Black Cat</title></head> <img 
src=blackcat.gif /> <script type="text/javascript">alert('If you see this, your\'re 
vulernable to XSS!');</script>

Output of above code in website form for clarification: http://hills.ccsf.edu/~wly3/cs132a/lab4.cgi

Two questions:

1) How should I modify this code to incorporate escapeHTML and to remove unnecessary code? (I'm not sure which requires/includes I need)

module CgiHelper

require 'cgi'
require "erb"
include ERB::Util

  def h
    #code
  end

2) How should I modify the ERB in the beginning so that it works with the "h" method?

Any help is appreciated. Trial and error hasn't returned results for a while.

Это было полезно?

Решение

1) Create the h helper method

module CgiHelper
  require "erb"
  include ERB::Util

  def h(s)
    html_escape(s)
  end
end

2) Use the h helper method

<code>
  <%= h(the_string) %>
</code>
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top