Skip to content

Commit

Permalink
implement distinct_of validator
Browse files Browse the repository at this point in the history
  • Loading branch information
syphax-bouazzouni committed Feb 28, 2023
1 parent 05bb6cb commit fb62419
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
2 changes: 2 additions & 0 deletions lib/goo/validators/enforce.rb
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ def enforce(inst,attr,value)
check Goo::Validators::DataType, inst, attr, value, opt, Float
when :symmetric
check Goo::Validators::Symmetric, inst, attr, value, opt
when /^distinct_of_/
check Goo::Validators::DistinctOf, inst, attr, value, opt, opt
when Proc
call_proc(opt, inst, attr)
when /^max_/, /^min_/
Expand Down
36 changes: 36 additions & 0 deletions lib/goo/validators/implementations/distinct_of.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
module Goo
module Validators
class DistinctOf < ValidatorBase
include Validator

key :distinct_of_

error_message ->(obj) { "`#{@attr}` must be distinct of `#{@property}`"}

validity_check -> (obj) do
return true if self.class.empty_value?(@value)

self.distinct?(@inst, @property, @value)
end

def initialize(inst, attr, value, key)
super(inst, attr, value)
@property = property(key)
end

def property(opt)
opt[self.class.ids.size..opt.length].to_sym
end

def distinct?(inst, property, value)
target_values = self.class.attr_value(property, inst)
current_values = Array(value)

!current_values.any?{ |x| self.find_any?(target_values, x)}
end
def find_any?(array, value)
array.any?{ |x| self.class.equivalent_value?(value, x)}
end
end
end
end

0 comments on commit fb62419

Please sign in to comment.