Sanitize text before saving it into Active Record
Ruby
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
lib
test
.gitignore
Gemfile
MIT-LICENSE
README.md
Rakefile
string_sanitize.gemspec

README.md

String Sanitize

StringSanitize is a ruby gem that use Sanitize (https://github.com/rgrove/sanitize) gem to sanitize all the string and text fields before saving them to the database. Do read about it to understand what sanitization is happening on your data

Setup

Add the gem to your Gemfile and run the bundle command to install it.

gem "string_sanitize"

And then add it to your ActiveRecord model using its directive sanitize_text

class User < ActiveRecord::Base
  sanitize_text :basic => [:html_description], :except => [:serialized_text], :strict => true
end

Logic Followed

  • If the attribute is in :except list, its whitelisted and not processed.
  • If the attribute is of type :string, then its Sanitized completely. If you want HTML content, you should make it :text
  • If the attribute is of type :text, only one of the below sanitizes happen
    • If the attribute is in :allow_links list, Only anchor tags are allowed
    • If the attribute is in :basic list, Basic HTML is allowed. Sanitize::Config:BASIC
    • For every other attribute of type :text
      • If :strict is true
        • Only non HTML is content is allowed
      • Else
        • Only elements b, em, i, strong, u are allowed. Basically, Sanitize::Config:RESTRICTED is applied

Everything else

Please check Sanitize's default configurations at https://github.com/rgrove/sanitize/tree/master/lib/sanitize/config.

You can override Sanitize::Config::BASIC to suit your application needs. Everything else is probably just fine IMO.

Feel free to fork and make this better, I will be glad to merge your changes if they are relevant to everyone.

A big thanks to Ryan Grove (https://github.com/rgrove) for making such an awesome gem Sanitize (https://github.com/rgrove/sanitize)