Repository navigation
Use clusivity for numericality with :in or :within - #44467
skipkayhil wants to merge 1 commit into
Conversation
|
Echoing Rafael's question from #44465 (comment), what would be the benefit of using this instead of |
|
I agree it probably makes (more?) sense to use |
a8a25c1 to
8b906b7
Compare
There was a problem hiding this comment.
Theoretically, this should work with an Enumerable too, yes?
| def test_validates_numericality_with_in_array | |
| Topic.validates_numericality_of :approved, in: [1, 3] | |
| def test_validates_numericality_with_in_enumerable | |
| Topic.validates_numericality_of :approved, in: [1, 3].each |
There was a problem hiding this comment.
I'm not sure about removing this. I understand why -- String responds to include? -- but I wonder if we should specifically check for String and raise an ArgumentError. Or perhaps check value.respond_to?(:include?) && !value.is_a?(Enumerable). (This would negate my previous suggestion involving CLUSIVITY_CHECKS.any? { ... }.)
There was a problem hiding this comment.
Allowing an arbitrary Enumerable also impacts error messages. For example, with validates_numericality_of :foo, in: Set[1, 3], the error message is "Foo must be in #<Set: {1, 3}>".
This message comes from
Whereas the error message for InclusionValidator is simply
I'm not sure of the best way to deal with that. One possibility is to change the 2nd argument of errors.add conditional on the type of option_value. e.g.:
| record.errors.add(attr_name, option, **filtered_options(value).merge!(count: option_value)) | |
| error_type = option_value.is_a?(Range) ? option : :inclusion | |
| record.errors.add(attr_name, error_type, **filtered_options(value).merge!(count: option_value)) |
Or:
| record.errors.add(attr_name, option, **filtered_options(value).merge!(count: option_value)) | |
| if option_value.is_a?(Range) | |
| record.errors.add(attr_name, option, **filtered_options(value).merge!(count: option_value)) | |
| else | |
| record.errors.add(attr_name, :inclusion, **filtered_options(value)) | |
| end |
Previously, only ranges were allowed, but this change uses the existing Clusivity module to validate against anything with an include? method.
8b906b7 to
c97d414
Compare
|
Pushed an update with the trivial changes. On thinking about this more, I'm now leaning more towards deprecating the |
I agree that using I would be more inclined to improve the |
Summary
Previously, only ranges were allowed, but this change uses the existing
Clusivity module to validate against anything with an include? method.
Other Information
Fixes #44465