Created
August 4, 2017 10:24
-
-
Save pashagray/30912f4a9de487bbbc38754aeda78c79 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'dry-validation' | |
class BulkPeriodValidator(array_of_periods) | |
@array_of_periods = array_of_periods | |
@schema = Dry::Validation.Schema do | |
key(:array).required(:array?, :unique_by_endless_and_trial?) | |
configure do | |
# http://dry-rb.org/gems/dry-validation/error-messages/ | |
def self.messages | |
Dry::Validation::Messages.default.merge( | |
en: { errors: { unique_by_endless_and_trial?: 'must be unique values' } } | |
) | |
end | |
# http://dry-rb.org/gems/dry-validation/custom-predicates/ | |
def unique_by_endless_and_trial?(value) | |
values = value.select { |elem| [elem.endless, elem.trial] } | |
values.size == values.uniq.size | |
end | |
end | |
end | |
def valid? | |
!schema.(array: @array_of_periods).messages.any? | |
end | |
def errors | |
schema.(array: @array_of_periods).messages | |
end | |
end | |
period_validator = BulkPeriodValidator.new(array: your_array_of_periods) | |
period_validator.valid? | |
period_validator.errors |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment