Today I Learned

hashrocket A Hashrocket project

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
See More #rails TILs
Looking for help? Hashrocket has been an industry leader in Ruby on Rails since 2008. Rails is a core skill for each developer at Hashrocket, and we'd love to take a look at your project. Contact us and find out how we can help you.