Sha256: 5198f89bfd19339b7b72dd498c417e8e74c89fac2a2da82c59ca7312f73e4aa3

Contents?: true

Size: 1.72 KB

Versions: 1

Compression:

Stored size: 1.72 KB

Contents

require "attr_extras/explicit"
require "banktools-gb/errors"

module BankTools
  module GB
    class AccountNumberWithSortCode
      extend AttrExtras.mixin

      ACCOUNT_NUMBER_MIN_LENGTH = 6
      ACCOUNT_NUMBER_MAX_LENGTH = 10
      SORT_CODE_LENGTH = 6

      pattr_initialize [ :account_number, :sort_code ]

      def valid?
        errors.none?
      end

      def errors
        errors = []
        errors << :account_number_is_too_short if account_number_is_too_short?
        errors << :account_number_is_too_long if account_number_is_too_long?
        errors << :sort_code_with_wrong_length if sort_code_with_wrong_length?
        errors << :sort_code_with_invalid_characters if any_non_digits?(compact_sort_code)
        errors << :account_number_with_invalid_characters if any_non_digits?(compact_account_number)
        errors << :account_number_does_not_match_sort_code unless valid_account_number_with_sort_code?
        errors
      end

      private

      def valid_account_number_with_sort_code?
        UkAccountValidator::Validator.new(compact_account_number, compact_sort_code).valid?
      end

      def sort_code_with_wrong_length?
        compact_sort_code.length != SORT_CODE_LENGTH
      end

      def account_number_is_too_short?
        compact_account_number.length < ACCOUNT_NUMBER_MIN_LENGTH
      end

      def account_number_is_too_long?
        compact_account_number.length > ACCOUNT_NUMBER_MAX_LENGTH
      end

      def any_non_digits?(number)
        number.match(/\D/)
      end

      def compact_sort_code
        compact(sort_code)
      end

      def compact_account_number
        compact(account_number)
      end

      def compact(number)
        number.gsub(/[\s-]/, "")
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
banktools-gb-0.5.0 lib/banktools-gb/account_number_with_sort_code.rb