Since Rails 7.1, the preferred way to do this is now with normalizes. I've also substituted squish for strip as suggested in the other answers, as it is usually (but not always) what I want.
class User < ActiveRecord::Base
normalizes :username, with: -> name { name.squish }
end
User.normalize_value_for(:username, " some guy\n")
# => "some guy"
Note that just like apneadiving's answer about updating the setter method, this will also avoid the confusion that can arise from using a callback that fires on saving a record, but doesn't run on a newly instantiated (but not saved) object:
# using a before_save callback
u = User.new(usernamename: " lala \n ")
u.name # => " lala \n "
u.save
u.name # => "lala"
# using normalizes or overriding the setter method
u = User.new(usernamename: " lala ")
u.name # => "lala"
u.save
u.name # => "lala"