Active Model Validates Intersection Of
A custom validation for Active Model that check if an array is included in another one.
Identical to the method validates_inclusion_of from ActiveModel but for array comparison.
Consider an User model that have some set of "default" permissions.
class User < ActiveRecord::Base
DEFAULT_PERMISSION = ["read", "write", "share"]
validates_intersection_of :permission, in: DEFAULT_ROLES
end
If you want to validate your user based on an array:
user = User.new(permission: ["read", "share"])
user.valid? #true
user = User.new(permission: ["read", "admin"])
user.valid? #false
This active model custom validation is for you!
Installation
Add this line to your application's Gemfile:
gem 'active_model_validates_intersection_of'
And then execute:
$ bundle
Or install it yourself as:
$ gem install active_model_validates_intersection_of
Usage
in:parameter is requiredmessage:is optional
class User < ActiveRecord::Base
DEFAULT_PERMISSION = ["read", "write", "share"]
validates_intersection_of :permission, in: DEFAULT_ROLES
end
class User < ActiveRecord::Base
DEFAULT_PERMISSION = ["read", "write", "share"]
validates_intersection_of :permission, in: DEFAULT_ROLES, message: "invalid permission"
end
You can also use the custom validation directly:
class User < ActiveRecord::Base
DEFAULT_PERMISSION = ["read", "write", "share"]
validates_with ActiveModelValidatesIntersectionOf::Validator, attributes: [:permission], in: VALID_ARRAY
end
License
The gem is available as open source under the terms of the MIT License.
Contributing
First of all, thank you for wanting to help!
- Fork it.
- Create a feature branch -
git checkout -b more_magic - Add tests and make your changes
- Check if tests are ok -
rake spec - Commit changes -
git commit -am "Added more magic" - Push to Github -
git push origin more_magic - Send a pull request! :heart: