Normalization Attributes in Rails
In Rails 7.1, attribute normalization was introduced. This gives us an easy way to clean up data before persistence, or other actions.
class Contact < ApplicationRecord
normalizes :phone, with: -> (phone) { phone.gsub(/\D/, "") } # remove non-number chars
end
The above ensures that before save, a phone number like 904-123-4567
gets converted to 9041234567
.
In Rails 8, attribute normalization was backported to ActiveModel. So you can also use these methods in ActiveModels (re: Form objects) -
class ContactForm
include ActiveModel::Attributes
include ActiveModel::Attributes::Normalization
attribute :phone
normalizes :phone, with: -> (phone) { phone.gsub(/\D/, "") }
end
contact = ContactForm.new
contact.phone = "904-123-4567"
contact.phone # 9041234567
Tweet