module HasValidations

HasValidations provides methods to enable validations

Constants

MAX_POLICY_LENGTH

Public Class Methods

included(base) click to toggle source
# File lib/geoengineer/utils/has_validations.rb, line 9
def self.included(base)
  base.extend(ClassMethods)
end

Public Instance Methods

errors() click to toggle source

This method will return a list of errors if not valid, or nil

# File lib/geoengineer/utils/has_validations.rb, line 31
def errors
  execute_lifecycle(:before, :validation) if self.respond_to? :execute_lifecycle
  errs = []
  self.class.validations.each do |validation|
    errs << (validation.is_a?(Proc) ? self.instance_exec(&validation) : self.send(validation))
  end
  # remove nils
  errs = errs.flatten.select { |x| !x.nil? }
  errs
end
validate_at_least_one_present(attributes) click to toggle source

Validates that at least one of the specified attributes is present

# File lib/geoengineer/utils/has_validations.rb, line 66
def validate_at_least_one_present(attributes)
  errs = []
  present = attributes.select { |attribute| !self[attribute].nil? }.count
  errs << "At least one of #{attributes.join(', ')} must be defined" unless present.positive?
  errs
end
validate_cidr_block(cidr_block) click to toggle source

Validates CIDR block format Returns error when argument fails validation

# File lib/geoengineer/utils/has_validations.rb, line 53
def validate_cidr_block(cidr_block)
  return "Empty cidr block" if cidr_block.nil? || cidr_block.empty?
  return if NetAddr::CIDR.create(cidr_block)
rescue NetAddr::ValidationError
  return "Bad cidr block \"#{cidr_block}\" #{for_resource}"
end
validate_only_one_present(attributes) click to toggle source

Validates that ONLY one of the specified attributes is present

# File lib/geoengineer/utils/has_validations.rb, line 74
def validate_only_one_present(attributes)
  errs = []
  present = attributes.select { |attribute| !self[attribute].nil? }.count
  errs << "Only one of #{attributes.join(', ')} can be defined" unless present == 1
  errs
end
validate_policy_length(policy) click to toggle source
# File lib/geoengineer/utils/has_validations.rb, line 60
def validate_policy_length(policy)
  return unless policy.to_s.length >= MAX_POLICY_LENGTH
  "Policy is too large - must be less than #{MAX_POLICY_LENGTH} characters"
end
validate_required_attributes(keys) click to toggle source

Validation Helper Methods

# File lib/geoengineer/utils/has_validations.rb, line 43
def validate_required_attributes(keys)
  errs = []
  keys.each do |key|
    errs << "#{key} attribute nil for #{self}" if self[key].nil?
  end
  errs
end