Low commit activity in last 3 years
No release in over a year
Normalize ActiveRecord attributes
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies
 Project Readme

Normalize Attributes

Tests Code Climate Gem Gem

Sometimes you want to normalize data before saving it to the database like downcasing e-mails, removing spaces and so on. This Rails plugin allows you to do so in a simple way.

Usage

To install:

gem install normalize_attributes

Then on your model:

class User < ActiveRecord::Base
  normalize :email, with: :downcase
end

The example above will normalize your :email attribute on the before_save callback.

You can specify multiple attributes

normalize :email, :username, with: :downcase

You can use a block

normalize :name do |value|
  value.squish
end

You can combine both

normalize :name, with: :downcase do |value|
  value.squish
end

The squish method is the default normalizer for strings. All you need to is specify the attribute:

normalize :content

The compact method is the default normalizer for arrays (when using serialize method):

class User < ActiveRecord::Base
  serialize :preferences, Array
  normalize :preferences
end

The normalize method is aliased as normalize_attributes, normalize_attribute, normalize_attr, and normalize_attrs.

You can normalize the attribute before type casting; this is specially useful for normalizing dates and numbers.

class Product
  normalize(:price, raw: true) {|v| Money.new(v).to_f }
end

You can also use it with ActiveModel::Model classes.

class UserForm
  include ActiveModel::Model
  include ActiveModel::Attributes
  include ActiveModel::Validations::Callbacks
  include NormalizeAttributes::Callbacks

  attribute :username
  normalize :username
end

Maintainer

Contributors

Contributing

For more details about how to contribute, please read https://github.com/fnando/normalize_attributes/blob/main/CONTRIBUTING.md.

License

The gem is available as open source under the terms of the MIT License. A copy of the license can be found at https://github.com/fnando/normalize_attributes/blob/main/LICENSE.md.

Code of Conduct

Everyone interacting in the normalize_attributes project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the code of conduct.