acts_as_normalized is a Rails plugin that automatically normalizes selected ActiveRecord model attributes before validation. By default it strips leading and trailing whitespaces. You can set :nilify option to replace empty strings with nil.
If optional block is given, it is called with already stripped attribute value and may be used to write your own normalization code.
./script/plugin install git://github.com/vits/acts_as_normalized.git
class Person < ActiveRecord::Base # Give one or more attribute names acts_as_normalized :first_name, :last_name # Use :nilify option to replace empty strings with nil acts_as_normalized :address, :nilify => true # Use block to do custom normalization # Value is already stripped before calling block # # NB you should not use return statement in block! acts_as_normalized :phone_number |value| value.is_a?(String) ? value.gsub(/\W/, '') : value end end person = Person.new # empty strings preserved by default person.first_name = ' ' person.first_name # => '' person.last_name = " \tSimpson \n " person.last_name # => 'Simpson' # empty string becomes nil if :nilify => true person.address = ' ' person.address = nil # custom normalization person.phone_number = '(555) 123.4567' person.phone_number # => '5551234567'
Some ideas for this plugin are taken from acts_as_stripped and attribute_normalizer.
Copyright © 2009 Vitauts Stočka, released under the MIT license.