module Validate

Validate.rb can be used independently by calling {Validate.validate} or included in classes and modules.

@example Validating an object using externally defined metadata

Address = Struct.new(:street, :city, :state, :zip)
Validate::Validators.define(Address) do
  attr(:street) { not_blank }
  attr(:city) { not_blank }
  attr(:state) { not_blank & length(2) }
  attr(:zip) { not_blank & match(/[0-9]{5}(\-[0-9]{4})?/) }
end
puts Validate.validate(Address.new)

@example Validating an object using metdata defined in class

class Address < Struct.new(:street, :city, :state, :zip)
  include Validate
  validate do
    attr(:street) { not_blank }
    attr(:city) { not_blank }
    attr(:state) { not_blank & length(2) }
    attr(:zip) { not_blank & match(/[0-9]{5}(\-[0-9]{4})?/) }
  end
end
puts Validate.validate(Address.new)

typed: strict

typed: strict

typed: strict

typed: strict

Constants

VERSION

Public Class Methods

included(base) click to toggle source

Hook to allow for inclusion in class or module

# File lib/validate.rb, line 71
def self.included(base)
  base.extend(ClassMethods)
end
validate(object, as: object.class) click to toggle source

Validate an object and get constraint violations list back

@param object [Object] object to validate @param as [Symbol, Class] (object.class) validator to use, defaults to

object's class

@return [Array<Constraint::Violation>] list of constraint violations

# File lib/validate.rb, line 53
def self.validate(object, as: object.class)
  violations = []
  Scope.current
       .validator(as)
       .validate(Constraints::ValidationContext.root(object, violations))
  violations.freeze
end
validator?(name) click to toggle source

Check if a given validator exists

@param name [Symbol, Class] validator to check

@return [Boolean] `true` if validator is present, `else` otherwise

# File lib/validate.rb, line 66
def self.validator?(name)
  Scope.current.validator?(name)
end