Permalink
Browse files

Fallback when previous_value doesn't respond to #next.

For example, floating point attributes won't respond to #next, so in
this case fall back to adding 1. This is not perfect, but it seems
to rarely occur in practice since I wasn't able to find anyone else
complaining about it.
  • Loading branch information...
1 parent 3d94390 commit 9d0c74e4bfc2a1abb509cc4bdc1756ffdb561b9d @sjmadsen sjmadsen committed Sep 20, 2011
Showing with 5 additions and 1 deletion.
  1. +5 −1 lib/shoulda/matchers/active_model/validate_uniqueness_of_matcher.rb
View
6 lib/shoulda/matchers/active_model/validate_uniqueness_of_matcher.rb
@@ -116,7 +116,11 @@ def validate_after_scope_change
# Assume the scope is a foreign key if the field is nil
previous_value ||= 0
- next_value = previous_value.next
+ next_value = if previous_value.respond_to?(:next)
+ previous_value.next
+ else
+ previous_value + 1
+ end
@subject.send("#{scope}=", next_value)

5 comments on commit 9d0c74e

@joshuaclayton

If previous value doesn't respond to next, how about calling to_s and then calling next?

"1.25".next # "1.26"
@sjmadsen
Light Year Software, LLC member

That works great, too. I committed and pushed that change. Should I send a pull request?

@joshuaclayton

Yep, that sounds great. We usually go through open-source pull requests on Friday

@pcastellazzi

I have been hit by this problem too. I been trying a sligthly different workaround:

next_value = @subject.class.order(scope).last.to_s.next

This also solve the case when next_value is already in the database. I am not sure if it's a better solution because it make validate_uniqueness_of ActiveRecord specific. I would like to hear your thoughts about this.

@sjmadsen
Light Year Software, LLC member

I minimize the amount of data in my tables for test runs and do not use fixtures. When these tests run, there is only one record in the database: the one I saved explicitly to test the uniqueness requirement. The simpler fall-back for next_value is enough in this case.

Please sign in to comment.