What is the fastest way to validate that a field has no more than n words?

Posted by James A. Rosen on Stack Overflow See other posts from Stack Overflow or by James A. Rosen
Published on 2010-05-04T01:43:32Z Indexed on 2010/05/04 1:48 UTC
Read the original article Hit count: 238

I have a Ruby-on-Rails model:

class Candidate < ActiveRecord::Base
  validates_presence_of :application_essay
  validate :validate_length_of_application_essay

  protected

  def validate_length_of_application_essay
    return if application_essay.blank? # don't add a second error message if they didn't fill it out
    errors.add(:application_essay, :too_long), unless ...
  end
end

Without dropping into C, what is the fastest way to check that the application_essay contains no more than 500 words? You can assume that most essays will be at least 200 words, are unlikely to be more than 5000 words, and are in English (or the pseudo-English sometimes called "business-ese"). You can also classify anything you want as a "word" as long as your classification would be immediately obvious to a typical user. (NB: this is not the place to debate what a "typical user" is :) )

© Stack Overflow or respective owner

Related posts about ruby

Related posts about ruby-on-rails