before_save, strip a string
Asked Answered
G

2

8

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

I'm using

before_save do
  self.username.strip!
end

but it doesn't seem to work, am i missing something ?

Goodsell answered 28/1, 2014 at 9:9 Comment(2)
You're missing the assignment self.username = self.username.strip!Boiney
@Hitham S. AlQadheeb, There is no need for the assignment. using strip! already do that.Digester
C
21

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

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

Btw, I prefer squish

Contumacious answered 28/1, 2014 at 9:11 Comment(5)
Thanks for answering, it worked just fine. Can you explain to me why you prefer squish over strip?Goodsell
squish removes all silly blanks, strip only removes leading and trailingContumacious
Sounds cool, so i replace value.to_s.strip => value.to_s.squish right ?Goodsell
@daniel this was to avoid the nil possibilityContumacious
please use super(value.to_s.strip) instead of self[:attr] = value.to_s.strip if it's ActiveRecordArcboutant
D
0

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

Digester answered 28/1, 2014 at 9:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.