Peter Marklund

Peter Marklund's Home

Mon October 06, 2008
Programming

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

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?

Comments

denro said over 6 years ago:

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

--------------------------------------------------------------------------------