I’m refactoring my normalizes methods in Rails with tne new normalizes method. Lets take a look together.
class User < ActiveRecord::Base
normalizes :email, with: -> email { email.strip.downcase }
end
user = User.create(email: " CRUISE-CONTROL@EXAMPLE.COM\n")
user.email # => "cruise-control@example.com"
Code in my project before the refactoring, for the username i use the unicode_normalice function to return a normalized form of str, using Unicode normalizations NFC, NFD, NFKC, or NFKD.
def normalize_username
username.unicode_normalize!
self.username_lower = username.downcase
end
}
After refactoring the code it looks like this:
class User < ApplicationRecord
normalizes :username, with: -> username { username.unicode_normalize.strip.downcase }
end
And we have a bit more clean code with less functions to test.