Sha256: f2115aa056aef21b08c53ae975e310c6fc3684a6fd8b9a0e46c1de777a88c256

Contents?: true

Size: 1.38 KB

Versions: 1

Compression:

Stored size: 1.38 KB

Contents

require "shoulda-matchers"

module Shoulda
  module Matchers
    module ActiveModel
      def require_a_valid_telephone(attr = :telephone)
        RequireAValidTelephoneMatcher.new(attr)
      end

      class RequireAValidTelephoneMatcher< ValidationMatcher
        def initialize(attribute)
          @attribute = attribute
          @options = {}
        end

        def from(locale)
          @options[:locale] = locale
          self
        end

        def description
          "require #{@attribute} to be a valid telephone number"
        end

        def matches?(subject)
          super(subject)

          disallows_invalid_value and allows_valid_value
        end

        private

        def disallows_invalid_value
          return (disallows_value_of("123456") and disallows_value_of("(11)2222-3333")) if @options[:locale] == :usa
          return (disallows_value_of("123456") and disallows_value_of("(111)222-3333") and disallows_value_of("(11)81111-1111")) if @options[:locale] == :br
          disallows_value_of("123456")
        end

        def allows_valid_value
          return allows_value_of("(111)222-3333") if @options[:locale] == :usa
          return (allows_value_of("(11)2222-3333") and allows_value_of("(11)91111-1111")) if @options[:locale] == :br
          allows_value_of("(111)222-3333") and allows_value_of("(11)2222-3333")
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
validates_telephone-1.1.0 lib/validates_telephone/shoulda-matchers/require_a_valid_telephone_matcher.rb