Strip HTML in Ruby on Rails

    Code Security is very important nowadays, so I thought I'd show everyone how to automatically strip off any HTML, javascript, css, etc. tags in ruby on rails. Many malicious users often try to type in code that execute when another person is looking at what they typed(like a forum post, for instance). Some security issues caused by this are XSS(Cross Site Scripting) and CSRF(Cross Site Request Forgery). So if someone is going to enter in ANY text that will show up on your site, I'd recommend that you clean their text of code before it's entered into your website/software.

Here's how to clean a normal string:

string = "<b>Bob</b>"

string = string.gsub(/<\/?[^>]*>/,  "")


 
Also, another handy thing you can do is clean everything going into
your  database. This code will automatically clean any string or text
data in your database. You don't even have to enter in the name of
the columns you want cleaned.  All you have to do is change the name of the model(it's in orange below) and then enter in the code into your class model, ie: product.rb. And it will take care of the cleaning
for you:

 class Product < ActiveRecord::Base

  before_save :strip_html
  def strip_html # Automatically strips any tags from any string to text typed column
    for column in Product.content_columns
      if column.type == :string || column.type == :text # if the column is text-typed
        if !self[column.name].nil? # strip html from string if it's not empty
          self[column.name] = self[column.name].gsub(/<\/?[^>]*>/, "")
        end
      end
    end
  end



Keep in mind that this code will clean out ANYTHING that is in tags,
such as: <br><b><whatever><cheese><etc>

 

Comments(1)

Vidul says...
You can also use non-greedy matching: string.gsub(/<\/?.*?>/, "")

Add A Comment



simple_captcha.jpg
Type in the code above.



Powered_by_amethyst
Archive
Search
Tags
          Databases (1)
          General (2)
          Hosting (1)
          Hulihan Applications (2)
          Programming (1)
          Ruby (2)
          Ruby on Rails (3)
          Servers (1)
          Software (1)
view rss feed
This site is best displayed in FireFox 1.5+, IE 7+, and Opera 9+