I was noticing a lot of blank values in my Rails models. I found it a little longer to have to do @post.title.present? instead of my usual @post.title. On a large sized some normalization can go a long ways for you.

We will discuss a few methods.

First we have two gems:

The first and best is attribute_normalizer. This one includes a few data normalizers by default

  • :blank Will return nil on empty strings
  • :phone Will strip out all non-digit characters and return nil on empty strings
  • :strip Will strip leading and trailing whitespace.
  • :squish Will strip leading and trailing whitespace and convert any consecutive spaces to one space each


If you only desire to make the blank values nil then use the gem nilify_blanks


Next we will discuss the manual methods of doing this. I will show how to apply it for a single model, as a mixin, or as an extension to ActiveRecord::Base

For a Single Model:


class Post < ActiveRecord::Base
  before_save :normalize_blank_values

  def normalize_blank_values
    attributes.each do |column, value|
      self[column].present? || self[column] = nil
    end
  end
end


To Create a Mixin for Use in Many Models:

To Enable It in your model:


# config/initializers/normalize_blank_values.rb

module NormalizeBlankValues
  extend ActiveSupport::Concern

  included do
    before_save :normalize_blank_values
  end

  def normalize_blank_values
    attributes.each do |column, value|
      self[column].present? || self[column] = nil
    end
  end
end

And in your model:


class Post < ActiveRecord::Base
  include NormalizeBlankValues
end


To Extend ActiveRecord::Base to do it


# config/initializers/normalize_blank_values.rb

module NormalizeBlankValues
  extend ActiveSupport::Concern

  def normalize_blank_values
    attributes.each do |column, value|
      self[column].present? || self[column] = nil
    end
  end

  module ClassMethods
    def normalize_blank_values
      before_save :normalize_blank_values
    end
  end
end

ActiveRecord::Base.send(:include, NormalizeBlankValues)

And in your model:


class Post < ActiveRecord::Base
  normalize_blank_values
end


Related External Links: