automatically strip attributes of an ActiveRecord model

By | January 22, 2008

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).

  1. module ActiveRecord
  2.   class Base
  3.     #strips the value of the given attributes automatically
  4.     def self.auto_strip(*attrs)
  5.       attrs.each do |attr|
  6.         define_method((attr.to_s + '=').to_sym) { |val| write_attribute attr, val.to_s.strip }
  7.       end
  8.     end
  9.   end
  10. 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 …

Leave a Reply

*

* Copy This Password *

* Type Or Paste Password Here *

132,948 Spam Comments Blocked so far by Spam Free Wordpress