I like to keep my Active Record models as strict as possible. There are few things more enoying to me then having to deal with bad legacy data when a simple change to a database column to not allow NULL values or adding validation in a model to disalow ’’ could have saved hours of data massaging.

Enter the attribute_normalizer rails plugin

class Klass < ActiveRecord::Base
  
  # Can take an array of attributes if you want
  normalize_attributes :first_name, :last_name
  
end
object = Klass.new
# Blank normalizes to nil
object.first_name = ''
object.first_name # => nil

# Whitespace is also cleaned up 
object.last_name = "\tDeering\n"
object.last_name # => 'Deering'

And for more bonus points then I can throw at it also accepts blocks!

class Klass < ActiveRecord::Base
  
  normalize_attributes :home_phone_number, :office_phone_number_ do |value|
    return nil unless value.is_a?(String)
    value.gsub(/\W/, '').gsub(/^1/, '')
  end

  normalize_attributes :postal_code do |value|
    value.upcase.gsub(/\W/,'')
  end
  
end
object = Klass.new
# Your given block will be executed to normalize
object.home_phone_number = '+1 (555) 123.4567'
object.home_phone_number # => '5551234567'

# Normalization happens before any validations.
# This will surely help avoid a lot of regex within validates_format_of
object.postal_code = 't6m 2x2'
object.postal_code # => 'T6M2X2'

This has become standard on every one of my rails projects. I hope you can find a use for it also. I have some backend Ruby work coming up so I should get around to making this a gem soon.

Cheers,
Mike D.

I’m on Twitter