Rails before_validation strip whitespace best practices

Viewed 55479

I would like my User model to sanitize some input before before save. For now some simple whitespace stripping will do. So to avoid people registering with "Harry " and pretend to be "Harry", for example.

I assume it is a good idea to do this stripping before validation, so that the validates_uniqueness_of can avoid accidental duplicates.

class User < ActiveRecord::Base
  has_many :open_ids

  validates_presence_of :name
  validates_presence_of :email
  validates_uniqueness_of :name
  validates_uniqueness_of :email
  validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i

  before_validation :strip_whitespace, :only => [:name, :email, :nick]

  private
  def strip_whitespace(value)
    value.responds_to?('strip') ? value.strip : value
  end
end

However, this code comes with an error ArgumentError: wrong number of arguments (0 for 1). I assumed the callback would be passed the values.

Also: is this stripping actually a good idea? Or should I rather validate on space and tell the user that "Harry " contains invalid spacess (I want to allow "Harry Potter" but not "Harry\s\sPotter").

Edit: As pointed out in a comment, my code is wrong (which is why I was asking the question a.o.). Please make sure you read the accepted answer in addition to my question for the correct code and to avoid the same mistakes I made.

14 Answers

I like Karl's answer, but is there a way to do it without referencing each of the attributes by name? That is, is there a way to just run through the model attributes and call strip on each one (if it responds to that method)?

This would be desirable so I don't have to update the remove_whitespace method whenever I change the model.

UPDATE

I see that Karl implied that you might want to do this sort of thing. I didn't immediately know how it could be done, but here's something that works for me as described above. There' probably a better way to do it, but this works:

def clean_data
  # trim whitespace from beginning and end of string attributes
  attribute_names().each do |name|
  if self.send(name.to_sym).respond_to?(:strip)
    self.send("#{name}=".to_sym, self.send(name).strip)
  end
end

end

A better alternative is to overwrite the setter method and use value.squish. Its cleaner and you don't have to use before_validation:

class User < ActiveRecord::Base
  def name=(value)
    super(value.squish)
  end  
end
Related