module Aba::Validations

Constants

BECS_PATTERN
CREDIT_TRANSACTION_CODES
DEBIT_TRANSACTION_CODES
INDICATORS

Attributes

error_collection[RW]
errors[RW]

Public Class Methods

included(base) click to toggle source
# File lib/aba/validations.rb, line 12
def self.included(base)
  base.instance_eval do
    @_validations = {}
  end

  base.send :extend, ClassMethods
end
transaction_codes() click to toggle source
# File lib/aba/validations.rb, line 20
def self.transaction_codes
  DEBIT_TRANSACTION_CODES + CREDIT_TRANSACTION_CODES
end

Public Instance Methods

valid?() click to toggle source
# File lib/aba/validations.rb, line 24
def valid?
  !has_errors?
end

Private Instance Methods

has_errors?() click to toggle source

Run all validations

# File lib/aba/validations.rb, line 33
def has_errors?
  self.error_collection = []

  self.class.instance_variable_get(:@_validations).each do |attribute, validations|
    value = send(attribute)

    validations.each do |type, param|
      case type
      when :presence
        self.error_collection << "#{attribute} is empty" if value.nil? || value.to_s.empty?
      when :bsb
        unless((param && value.nil?) || value =~ /^\d{3}-\d{3}$/)
          self.error_collection << "#{attribute} format is incorrect"
        end
      when :max_length
        self.error_collection << "#{attribute} length must not exceed #{param} characters" if value.to_s.length > param
      when :length
        self.error_collection << "#{attribute} length must be exactly #{param} characters" if value.to_s.length != param
      when :integer
        if param
          self.error_collection << "#{attribute} must be a number" unless value.to_s =~ /\A[+-]?\d+\Z/
        else
          self.error_collection << "#{attribute} must be an unsigned number" unless value.to_s =~ /\A\d+\Z/
        end
      when :account_number
        if value.to_s =~ /\A[0\ ]+\Z/ || value.to_s !~ /\A[a-z\d\ ]{1,9}\Z/i
          self.error_collection << "#{attribute} must be a valid account number"
        end
      when :becs
        self.error_collection << "#{attribute} must not contain invalid characters" unless value.to_s =~ BECS_PATTERN
      when :indicator
        list = INDICATORS.join('\', \'')
        self.error_collection << "#{attribute} must be a one of '#{list}'" unless INDICATORS.include?(value.to_s)
      when :transaction_code
        self.error_collection << "#{attribute} must be one of #{Validations.transaction_codes.join(', ')}" unless Validations.transaction_codes.include?(value.to_i)
      end
    end
  end

  !self.error_collection.empty?
end