Obscenity Gem, a profanity filter.
Have you ever wanted to filter out certain words from user generated text in your web applications?
Recently, I worked on a project that targeted a younger audience. Users are able to input a name for something they create on the site and I wanted a way to prevent the posting of curse words.
Initially, I implemented this feature by creating an array of common curse words and looped through the users' input to see if it included curse words from the array. If it did , I would replace that word with asterisks. But then I found the Obscenity Gem, which is a profanity filter for Rails through ActiveModel. They have an extensive list of profane words and there's even an international list too, which certainly covered more bad words that I could list!
I really like the way Obscenity used regular expressions to reliably replace the bad words. Additionally they provide 6 different replacement methods, my favorite is the ability to replace the word with a custom string.
Here's a brief tutorial for how I implemented it in a Rails project:
1. In your application's Gemfile, include:
gem 'obscenity'
2. Bundle Install
3. To add the validation on your model:
require 'obscenity/active_model'
4. Inside the model, include:
validates :body, obscenity: { sanitize: true, replacement: "Censored" }
If you're running into problems with validations, try using a before_save call back instead:
before_save :filter_obscenity def filter_obscenity self.name = Obscenity.replacement("Censored").sanitize(name) end
Happy filtering!
https://github.com/tjackiw/obscenity











