Rails model validations have a host of options
that allow developers to write complex rules for clean data entry.
A common validation is to ensure that the length of a string is within a certain range.
For example, a user’s name should be between 2
and 20 characters.
This can be achieved using the length validator.
app/models/user.rb
For most part this gets the job done.
When a user model is created with a name less than 2 characters
or more than 30 characters,
an appropriate error is thrown,
Before
However not all attributes require a minimum or maximum length.
For example, a middle name can have a maximum length of 30 characters,
but it can be empty.
This is not possible with the current implementation of the length validator.
The length validation or a custom one would have to be written.
After
Thanks to this PR
which introduces extensions to the Range class,
the first or the last value of a range can be infinite.
This allows us to write the following validations,
This allows validations to be written in a more concise way.
The length validator now supports infinite ranges in the :in
and :within options.
This change is possible due to the Float::INFINITY
option which is a number that is always the largest in a comparison.
This is how the code looks now,