Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Parameter maximum value #1535

Closed
CharlesP opened this issue Dec 16, 2016 · 4 comments
Closed

Parameter maximum value #1535

CharlesP opened this issue Dec 16, 2016 · 4 comments

Comments

@CharlesP
Copy link

When adding a parameter (i.e. per_page), is there a way to set the maximum value?

The cleanest (only) way I've found so far is to pass the entire array of possible options:
optional :per_page, values: [*1..100], default: 10, type: Integer

Is there a better way to achieve this?

@dblock
Copy link
Member

dblock commented Dec 19, 2016

I'll label this as a feature request to support min and max, obviously there be dragons for non enumerable types ;)

@jlfaber
Copy link
Contributor

jlfaber commented Feb 1, 2017

#1568 added a new feature to the ValuesValidator that allows a Proc to be supplied for anonymous custom validations. Using this, your example above might look like this.

optional :per_page, values: { proc: ->(v) { v.positive? && v <= 100 } }, default: 10, type: Integer

I should note that the ValuesValidator already accepted Ranges, so you also could have done this.

optional :per_page, values: 1..100, default: 10, type: Integer

For both your original example and my Range alternative, the validator will call include? on the passed value. And, in both cases, that could result in up to 100 individual tests as it enumerates the Array or Range to determine whether the supplied value is a member. This is probably not catastrophic with a relatively small Range, but doing something like 0..1000000 could cause some performance problems.

A way to avoid this is (again) to use proc to test using cover? instead of include?, which will instead check that the value is between the endpoints of the range.

optional :per_page, values: { proc: ->(v) { (1..100).cover? v } }, default: 10, type: Integer

@dblock
Copy link
Member

dblock commented Feb 4, 2017

Should we close this?

@CharlesP
Copy link
Author

CharlesP commented Feb 6, 2017

@jlfaber Thanks, that's a big help.

@dblock Yes, this looks like a valid workflow for this.

@CharlesP CharlesP closed this as completed Feb 6, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants