Module: Webhookdb::Postgres::Validations
- Defined in:
- lib/webhookdb/postgres/validations.rb
Instance Method Summary collapse
-
#validates_all_or_none(*cols, predicate: :nil?) ⇒ Object
Ensures that either all of the passed columns are nil or none of them are.
-
#validates_at_least_one_of(*cols, predicate: :nil?) ⇒ Object
Ensures that at least one of the passed columns is not nil.
-
#validates_exactly_one_of(*cols, predicate: :nil?) ⇒ Object
Ensures that one and only one of the passed columns is not nil.
- #validates_ip_address(col) ⇒ Object
-
#validates_mutually_exclusive(*cols, predicate: :nil?) ⇒ Object
Ensures that only one of the passed columns is not nil.
Instance Method Details
#validates_all_or_none(*cols, predicate: :nil?) ⇒ Object
Ensures that either all of the passed columns are nil or none of them are.
15 16 17 18 19 20 21 22 |
# File 'lib/webhookdb/postgres/validations.rb', line 15 def validates_all_or_none(*cols, predicate: :nil?) truthy_cols = cols.find_all { |col| !self[col].send(predicate) } return if truthy_cols.empty? || truthy_cols.length == cols.length msg = "the columns #{cols[1..].join(', ')} must all be set or all be #{predicate.to_s.delete_suffix('?')}" self.errors.add(cols.first, msg) end |
#validates_at_least_one_of(*cols, predicate: :nil?) ⇒ Object
Ensures that at least one of the passed columns is not nil.
25 26 27 28 29 30 |
# File 'lib/webhookdb/postgres/validations.rb', line 25 def validates_at_least_one_of(*cols, predicate: :nil?) any_truthy = cols.any? { |col| !self[col].send(predicate) } return if any_truthy msg = "at least one of #{cols.join(', ')} must be not #{predicate.to_s.delete_suffix('?')}" self.errors.add(cols.first, msg) end |
#validates_exactly_one_of(*cols, predicate: :nil?) ⇒ Object
Ensures that one and only one of the passed columns is not nil.
33 34 35 36 |
# File 'lib/webhookdb/postgres/validations.rb', line 33 def validates_exactly_one_of(*cols, predicate: :nil?) self.validates_at_least_one_of(*cols, predicate:) self.validates_mutually_exclusive(*cols, predicate:) end |
#validates_ip_address(col) ⇒ Object
38 39 40 41 42 43 44 45 |
# File 'lib/webhookdb/postgres/validations.rb', line 38 def validates_ip_address(col) return if self[col].respond_to?(:ipv4?) begin IPAddr.new(self[col]) rescue IPAddr::Error self.errors.add(col, "is not a valid INET address") end end |
#validates_mutually_exclusive(*cols, predicate: :nil?) ⇒ Object
Ensures that only one of the passed columns is not nil.
7 8 9 10 11 12 |
# File 'lib/webhookdb/postgres/validations.rb', line 7 def validates_mutually_exclusive(*cols, predicate: :nil?) truthy_cols = cols.find_all { |col| !self[col].send(predicate) } multiple_set = truthy_cols.length > 1 return unless multiple_set self.errors.add(truthy_cols.first, "is mutually exclusive with other set columns #{truthy_cols[1..].join(', ')}") end |