ActiveCleaner to clean your fields in your Rails models

Some time ago, I released a tiny gem that helps me to clean some user generated fields: ActiveCleaner.

An app or a website allows user to enter some data through forms. In my models, I was constantly doing this:

before_validation :clean_title

def clean_title
  self.title = title.squish unless title.nil?
  self.title = nil if title.blank?

  true
end

Why ? Extra spaces mean extra storage. And it could ruin your indexes and your sortings. And I want that blank fields turn into nil.

I was bored to write this same stuff all over the models, I decided to write a tiny gem that does the job:

class Post
  include Mongoid::Document

  field :title
  clean :title, nilify: true
end

And voilà. It runs as a before_validation callback. As for now, it supports three cleaners:

  • :string, StringCleaner, the default one: cleans all the space characters. It turns " A \n \t title \t " into "A title".
  • :text, TextCleaner: like :string, but preserves new lines (with a max of two successive new lines). Useful when the field is rendered with the simple_format Rails helper.
  • :markdown, MarkdownCleaner: like :text, but preserves spaces in the beginning of lines (the indentation). Useful for… markdown!

You can write custom cleaners, and several more are to come. Don’t hesitate to tell me the useful missing ones.

The :nilify is an option, that which default is false. When true, it turns resulting blank string into nil.

The project pages:

Next article: Revamping this blog

Previous article: EYR - Refactoring from good to great (and live)

Maxime Garcia
Maxime Garcia
CTO @ Electra
Living in Paris