acts_as_sanitizable

Sanitizable concern to sanitize activerecord model attributes the way you like. E.g. very useful if you want to convert empty strings from your form params into nil

Dependencies

Ruby >= 1.9.3

Rails >= 3.2.0

Installation

Add acts_as_sanitizable to your Gemfile:

gem 'acts_as_sanitizable'

Download and install by running:

bundle install

Usage

Add the sanitizes method to your model to perform sanitization on specific attributes. You can define what type of sanitization you want to do by specifing a :with option or a block.

class User < ActiveRecord::Base   
  sanitizes :first_name, :last_name, with: :strip
  sanitizes :email, with: [:strip, :downcase]
  sanitizes :biography, with: ->(biography) { biography.squish }
  sanitizes :username do |username|
    # strip leading "@" characters as used in Twitter usernames
    username.strip.downcase.sub(/\A@/, '')
  end
end

The sanitizes method is aliased as acts_as_sanitizable.

Sanitization is performed before_validation so the sanitized content will only be visible after calling the valid? or save methods on your instance of the model.

Contexts

You can define when sanitization should be performed via :on. If no :on parameter is specified acts_as_sanitizable will sanitize on both, create and update.

class User < ActiveRecord::Base
  sanitizes :first_name, with: :strip, on: :create
  sanitizes :last_name, with: :strip, on: :update
end

Inheritance

class User < ActiveRecord::Base   
  sanitizes :first_name, :last_name, with: :strip
  sanitizes :email, with: [:strip, :downcase], on: :create
end

If you wish to not sanitize specific attributes on an inherited model you can call skip_sanitization_of. When you have been using a context in the sanitizer definition be sure to specify the same one when using skip_sanitization_of.

class Admin < User
  skip_sanitization_of :first_name
  skip_sanitization_of :email, on: :create
end

Reflection

You can return a list of all sanitized attributes by calling:

User.sanitizable_attributes # => [#<Sanitizable::AttributeSanitizer name: :first_name, ...>, ...]

User.sanitizable_attribute_names # => [:first_name, :last_name, ...]

Contributing to acts_as_sanitizable