12

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?

Michael Durrant
  • 93,410
  • 97
  • 333
  • 497
Hopstream
  • 6,391
  • 11
  • 50
  • 81
  • I don't know any config regrading that, but in case of before_validation hook you can check this: http://stackoverflow.com/questions/4294923/rails-3-strip-whitespace-before-validation-on-all-forms – sparrovv Nov 10 '11 at 14:09
  • See an [implementation here as well](http://railsforum.com/viewtopic.php?id=969). – Zabba Nov 10 '11 at 14:13

5 Answers5

9

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.

Michael Durrant
  • 93,410
  • 97
  • 333
  • 497
3

Use the strip_attributes gem:

https://github.com/rmm5t/strip_attributes

Jacob
  • 6,317
  • 10
  • 40
  • 58
2

I'd just have a filter that runs before validation and tears through all of the params to trim them. If you put it on your base controller class, you just set it and forget it.

jdc
  • 733
  • 3
  • 7
2

Indeed, this annoyed me a little too - so I wrote this

https://github.com/omarqureshi/AR-stripper

will publish this as a gem sooner or later but in the meantime just

gem 'stripper', :git => "git@github.com:omarqureshi/AR-stripper.git"

in your Gemfile will do

Omar Qureshi
  • 8,963
  • 3
  • 33
  • 35
0

You could also use a callback to strip the whitespace without using a gem.

Patricia.
  • 61
  • 6