Skip to content

Rails plugin that automatically normalizes selected ActiveRecord model attributes before validation.

License

Notifications You must be signed in to change notification settings

vits/acts_as_normalized

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

About

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.

Installation

./script/plugin install git://github.com/vits/acts_as_normalized.git

Usage

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'

Credits

Some ideas for this plugin are taken from acts_as_stripped and attribute_normalizer.

License

Copyright © 2009 Vitauts Stočka, released under the MIT license.

About

Rails plugin that automatically normalizes selected ActiveRecord model attributes before validation.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages