You know the situation when some users add a couple of whitespaces to the front or/and the end of a value they just entered into your application? Yeah, and in most cases we dont really want those blanks in our data. But on the other hand we can not really blame them because sometimes it just happens by mistake. Just imagine your cat played with the space bar while you quickly went for a coffee. The solution is not to get rid of the cat, … Its rahter an extension. And no not to your cat - small extension to ActiveRecord
Bung this snippet into a file in your applications lib
folder and don’t forget to require
it within the environment.rb
(Alternatively you could use the new initializers of Rails 2.0).
- module ActiveRecord
- class Base
- #strips the value of the given attributes automatically
- def self.auto_strip(*attrs)
- attrs.each do |attr|
- define_method((attr.to_s + '=').to_sym) { |val| write_attribute attr, val.to_s.strip }
- end
- end
- end
- end
After that you can do the following to your ActiveRecord
models:
class User < ActiveRecord::Base
auto_strip :firstname, :lastname
end
[/ruby]
Now the attributes firstname
and lastname
will never ever hold values including whitespaces in front and the end. Note: the cat is still alive …