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?
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.
Use the strip_attributes
gem:
https://github.com/rmm5t/strip_attributes
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With