before_save, strip a string before_save, strip a string ruby-on-rails ruby-on-rails

before_save, strip a string


You'd rather update the setter instead of polluting your model with callbacks:

def username=(value)  self[:username] = value.to_s.stripend

Btw, I prefer squish


If you want to remove only leading and trailing white space you can use .strip!

But as you said:

I'm trying to strip the whitespaces of the variable Username in my User Model.

I think actually you want to remove all spaces following should do:

.gsub(/\s+/, "")

EDIT:

Oh yes, You can also use Rail's built-in method squish()

thanx to apneadiving for reminding