automatically strip attributes of an ActiveRecord model

published on January 22, 2008 by Michal
category: Ruby on Rails

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

RUBY:
  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:

RUBY:
  1. class User <ActiveRecord::Base
  2.   auto_strip :firstname, :lastname
  3. end

Now the attributes firstname and lastname will never ever hold values including whitespaces in front and the end. Note: the cat is still alive ...

1 Star2 Stars3 Stars4 Stars5 Stars (3 votes, average: 4 out of 5)
Loading ... Loading ...

Leave a Reply


Please surround code with [asp]..[/asp], [javascript]..[/javascript], [php]..[/php], [html]..[/html] to highlight source code within your comments.

Currently highest rated articles on webdevbros: