Counting words in rail checking

I use the following check to count words in rails (I got an example from Rails docs), but this is not really accurate:

validates :body, :length => { :minimum => 50, :maximum => 300, :tokenizer => lambda { |str| str.scan(/\w+/) }, :too_short => "must have at least %{count} words", :too_long => "must have at most %{count} words" } 

The user tried to post something that contains 291 words (which gives the word Word), and it was rejected as too long. I do not know exactly what is wrong with the expression that is used, or what might be a good expression to provide the exact number of words.

+4
source share
2 answers

Instead of scanning for / \ w + / you should scan / \ s + | $ / and decrease max by one, since the coincidence of the characters of the word \ w may be unexpected with unusual characters, since only A-Za-z0-9_- are valid.

+5
source

You can try:

 :tokenizer => lambda { |str| str.split } 
+1
source

Source: https://habr.com/ru/post/1389004/


All Articles