It's so simple! scrubby makes sure that all your attributes are cleaned up before they make their way into your models.


In environment.rb: do |config|
  config.gem 'scrubby'

At your application root, run:

$ sudo rake gems:install


By default, scrubby will strip extra whitespace from strings, and turn blank strings into nil values:

class User < ActiveRecord::Base
  scrub :first_name, :middle_name, :last_name

>> u = => " Steve", :middle_name => "  ", :last_name => "Richert ")
=> #<User first_name: "Steve", middle_name: nil, last_name: "Richert">

Or you can override the default behavior, just by defining a scrub instance method:

class User < ActiveRecord::Base
  scrub :first_name, :middle_name, :last_name

  def scrub(value)

>> u = => "Steve", :last_name => "Richert")
=> #<User first_name: "STEVE", middle_name: "", last_name: "RICHERT">

And defining your own scrubbers inline is super easy:

class User < ActiveRecord::Base
  scrub(:first_name, :last_name){|v| v.blank? ? nil : v.titleize }

  scrub :middle_name do |value|
    initials = value.split(" ").map{|n| n.first.upcase + "." }
    initials.empty? ? nil : initials.join(" ")

class Admin < User
  scrub(:middle_name){ nil }

>> u = => "stephen", :middle_name => "joel michael", :last_name => "richert")
=> #<User first_name: "Stephen", middle_name: "J. M.", last_name: "Richert">
>> a = => "stephen", :middle_name => "joel michael", :last_name => "richert")
=> #<Admin first_name: "Stephen", middle_name: nil, last_name: "Richert">

How It Works

It's pretty straightforward, and there's nothing all that fancy happening behind the scenes.

Scrubbing happens only when attributes are set. That way, no time is wasted scrubbing every time an attribute is retrieved.

Scrubbing is done at the write_attribute level, without stepping on ActiveRecord's toes by creating a bunch of unnecessary setter methods.

Inheritance is respected, just as you'd expect, down through model subclasses. Scrubbers are overridden in subclasses with no problem.


Those of you who are familiar with attribute_normalizer[] will recognize the how scrubby looks and feels, and that's no accident! attribute_normalizer has a simple, clean and effective interface.

But scrubby was written to be an improvement on what's happening behind the scenes, particularly with regards to inheritance and avoiding unnecessary method definitions. Basically, the idea was to really simplify the back-end of an already awesome interface, and to gear it specifically toward ActiveRecord.


  • Fork the project

  • Make your feature addition or bug fix

  • Add, change or remove corresponding tests

  • Commit (please don't change Rakefile or VERSION)

  • Send me a pull request

Copyright © 2010 Steve Richert. See LICENSE for details.