Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove whitespace from Model attributes?

What's the simplest way to make sure models trim leading and trailing white space from string values.

One inconvenient way seems to be a before_save filter -- although for something as common as removing white space from strings, maybe there's some config that does that?

like image 818
Hopstream Avatar asked Nov 10 '11 14:11

Hopstream


2 Answers

There isn't a built-in global/config setting for the reason that you would not want to always do this, so it's better done on a case by case basis as you describe and with strip(field) in a before filter. There is a gem available though as detailed by Jacob.

I also advise caution when doing any manipulation to user values. A common best practice is to save "whatever" the user types, "warts and all" (well ok, spaces in this case). Then manipulate internally and format for display as required.
The main line of reasoning here being that when a user re-edits their info, it's better to give them 'exactly what they typed before' rather than getting caught up in what can end up being complicated validations and very brittle user interfaces.

Another sidenote, make sure to use 'data appropriate' fields, e.g. don't store dates in strings, it's asking for trouble.

like image 174
Michael Durrant Avatar answered Sep 19 '22 20:09

Michael Durrant


Use the strip_attributes gem:

https://github.com/rmm5t/strip_attributes

like image 38
Jacob Avatar answered Sep 18 '22 20:09

Jacob