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