Make Values Nil If Blank & Data Normalization In Rails

Posted By Weston Ganger

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
  normalize_blank_values
end

Related External Links:

Article Topic:Software Development - Ruby / Rails

Date:May 17, 2015