Skip to content

Commit

Permalink
implement inverse_of validator
Browse files Browse the repository at this point in the history
  • Loading branch information
syphax-bouazzouni committed Feb 28, 2023
1 parent 9707004 commit 9ea0be8
Show file tree
Hide file tree
Showing 3 changed files with 42 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 @@ -45,6 +45,8 @@ def enforce(inst,attr,value)
check Goo::Validators::DistinctOf, inst, attr, value, opt, opt
when /^superior_equal_to_/
check Goo::Validators::SuperiorEqualTo, inst, attr, value, opt, opt
when /^inverse_of_/
check Goo::Validators::InverseOf, inst, attr, value, opt, opt
when Proc
call_proc(opt, inst, attr)
when /^max_/, /^min_/
Expand Down
35 changes: 35 additions & 0 deletions lib/goo/validators/implementations/inverse_of.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
module Goo
module Validators
class InverseOf < ValidatorBase
include Validator

key :inverse_of_

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

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

return Array(@value).select{|x| not inverse?(@property,x, @inst)}.empty?
end

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

def inverse?(attr, value, source_object)
if self.class.respond_to?(attr, value)
target_values = self.class.attr_value(attr, value)
return target_values.any?{ |target_object| self.class.equivalent_value?(target_object, source_object)}
end

false
end


end
end
end
5 changes: 5 additions & 0 deletions lib/goo/validators/validator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,11 @@ def property(key)
key[ids.first.size..key.size].to_sym
end

def respond_to?(attr, object)
object && object.respond_to?(attr)
end


def equivalent_value?(object1, object2)
if object1.respond_to?(:id) && object2.respond_to?(:id)
object1.id.eql?(object2.id)
Expand Down

0 comments on commit 9ea0be8

Please sign in to comment.