This project is archived and is in readonly mode.
patch to add :count=>:words to validates_length_of
-
Pratik
- State changed from new to invalid
- Tag set to activerecord, patch
I don't think this is a very common requirement. I'd suggest releasing a plugin. Although, you can try emailing railscore mailing list to see if there is enough interest in the patch, in which case we can roll it in.
Thanks!
-
Jeremy Kemper
Seconded. I've never needed to count word length. If I did, I think I'd prefer adding a new kind of validation instead of another layer on validates_length_of.
-
David Lowenfels
It seemed like a natural fit to me because the existing rails code already is splitting on '', so I just modified it to optionally split on '\W'. It's a low hanging fruit. I thought a plugin would be overkill, as the core implementation happens on one line (which occurs twice in the code):
- value = value.split(//) if value.kind_of?(String)
- value = value.split(/#{split_token}/) if value.kind_of?(String)
The rest is just icing on the cake to extend the API, modify the validation error messages, and add tests.
-
Jeremy Kemper
- State changed from invalid to wontfix
Good point, David! We split with // so we get Unicode-aware character counts instead of byte length. This is an implementation detail that goes away in Ruby 1.9.
Perhaps we should accept an optional block to take an object and return a count.
validates_length_of(:essay, :minimum => 200, :too_short=>"Your essay must be at least %d words.") { |str| str.scan(/\w+/).size } -
David Lowenfels
@jeremy: that sounds like a good solution. Should I cook up a patch to accept a block?
-
Jeremy Kemper
cool, please do!
