Peter Marklund

Peter Marklund's Home


Rails Hack: Auto Strip ActiveRecord Attributes

We have a user who unintentially enters a space after his email address. It seems that a lot of times it makes sense to automatically strip ActiveRecord model attributes before they are validated. Inspired by this post I came out with my own auto_strip method that adds a before validation callback which seems less intrusive than redefining the attribute setter method:

# Sometimes users accidentally enter space before or after text in text fields. Let's not punish them
# with an error message for this.
module ActiveRecord
  class Base
    def self.auto_strip(*attributes)
      attributes.each do |attribute|
        before_validation do |record|
          record.send("#{attribute}=", record.send("#{attribute}_before_type_cast").to_s.strip) if record.send(attribute)

Now in my ActiveRecord model I can say for example:

  auto_strip :price, :vat, :max_tickets

Maybe auto stripping would be useful as an option to the Rails validation macros?

1 comment(s)


denro said 2008-11-28 10:31:

would be great to have this as a plugin, dont you think?